如何判断DOM节点是否展现

86 阅读2分钟

元素展现判定规则

  • 部分展现:元素有一部分出现在视口,就算作展现
  • 完全展现:整个元素出现在视口

实现

1. 获取视口大小

宽度window.innerWidth; 高度window.innerHeight

Similarly, the interior height of the window (that is, the height of the layout viewport) can be obtained using the innerHeight property. That measurement also accounts for the height of the horizontal scroll bar, if it is visible.

简单来说,Window.innerWidth返回布局视口的宽度,Window.innerHeight返回布局视口的高度

2. 获取元素距离视口的位置

Element.getBoundingClientRect()返回一个DOMRect 对象,表示包含整个元素的最小矩形(包括padding和border-width)。

提供了以下属性描述矩形:

  • 大小:width、height。

    • box-sizing: content-box(标准盒子模型):DOMRect.width/DOMRect.height = 元素宽高(width/height) + 内边距(padding) + 边框宽度(border) = 元素内容区width/height + 内边距(padding) + 边框宽度(border)
    • box-sizing: border-boxDOMRect.width/DOMRect.height = 元素宽高(width/height) = 元素内容区width/height + 内边距(padding) + 边框宽度(border)
  • 位置:x/left、right、y/top、bottom。相对于视图窗口的左上角计算。 image.png

3. 判断元素是否展现在视口

需满足水平、垂直两个方向均在视口内。

部分展现

  • 水平方向满足在视口的条件:节点最左侧边在视口内节点最右侧边在视口内
    • left < innerWidth && right > 0
  • 垂直方向满足在视口的条件:节点顶部边在视口内节点底部边在视口内
    • top < innerHeight && bottom > 0;
function inViewport(el) {
    // 获取DOM节点距离视口左上角的距离
    const {top, bottom, left, right} = el.getBoundingClientRect();
    // 获取视口大小 innerWidth:视口宽度  innerHeight:视口高度
    const {innerWidth, innerHeight} = window;
    return left < innerWidth && right > 0 && top < innerHeight && bottom > 0;
}

完全展现

  • 水平方向满足在视口的条件:节点最左侧边在视口内节点最右侧边在视口内
    • left >= 0 && right <= innerWidth
  • 垂直方向满足在视口的条件:节点顶部边在视口内节点底部边在视口内
    • top >= 0 && bottom <= innerHeight
function inViewport(el) {
    const {top, bottom, left, right} = el.getBoundingClientRect();
    const {innerWidth, innerHeight} = window;
    return top >= 0 && bottom <= innerHeight && left >= 0 && right <= innerWidth;
}