如果指定的元素在可视窗口中可见,则返回 true
,否则返回 false
。
使用 Element.getBoundingClientRect()
和 window.inner(Width|Height)
值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true
来判断它是否部分可见。
const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; };
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10} elementIsVisibleInViewport(el); // false // (not fully visible) elementIsVisibleInViewport(el, true); // true // (partially visible)
更多代码 JavaScript 实用代码片段 请查看 https://www.7psus5.com/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂