如果指定的元素在可视窗口中可见,则返回 true ,否则返回 false 。
使用 Element.getBoundingClientRect() 和 window.inner(Width|Height) 值来确定给定元素是否在可视窗口中可见。 省略第二个参数来判断元素是否完全可见,或者指定 true 来判断它是否部分可见。
JavaScript 代码:
-
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;
-
};
JavaScript 代码:
-
// 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)
主要用来辩别一些 隐藏的菜单(下拉子菜单)
发表评论