美文网首页
2021-01-06如何优雅的判断元素是否进入当前视区

2021-01-06如何优雅的判断元素是否进入当前视区

作者: 夏天的风2020 | 来源:发表于2021-01-06 11:17 被阅读0次
    图片

    正文

    1. 使用元素位置判断元素是否在当前视区

    这种方法实现起来比较简单, 我们一步一步来。
    首先:编写一个 util 函数 isVisible,它将仅接收一个参数,即 element。

    export const isVisible = (el) => { };
    

    使用 getBoundingClientRect 获取该元素的位置

    const rect = el.getBoundingClientRect();
    

    将找到窗口的高度和宽度

    const vWidth = window.innerWidth || document.documentElement.clientWidth;
    
    
    const vHeight = window.innerHeight || document.documentElement.clientHeight;
    

    再编写一个函数,该函数基本上将接收 x 和 y 点,并使用elementFromPoint函数返回元素。

    const elementFromPoint = function (x, y) { 
      return document.elementFromPoint(x, y); 
    };
    

    检查元素是否在窗口内:

    // Return false if it's not in the viewport
    if (rect.right < 0 
      || rect.bottom < 0
      || rect.left > vWidth 
      || rect.top > vHeight) { 
      return false; 
    }
    

    边界检查:

    // Return true if any of its four corners are visible
     return (
       el.contains(elementFromPoint(rect.left, rect.top))
       || el.contains(efp(rect.right, rect.top))
       || el.contains(efp(rect.right, rect.bottom))
       || el.contains(efp(rect.left, rect.bottom))
     );
    

    完整代码:

    export const isVisible = (el) => {
      const rect = el.getBoundingClientRect();
      const vWidth = window.innerWidth || document.documentElement.clientWidth;
      const vHeight = window.innerHeight || document.documentElement.clientHeight;
      const efp = function (x, y) { return document.elementFromPoint(x, y); };
    
      // Return false if it's not in the viewport
      if (rect.right < 0 || rect.bottom < 0
                || rect.left > vWidth || rect.top > vHeight) { return false; }
    
      // Return true if any of its four corners are visible
      return (
        el.contains(
          elementFromPoint(rect.left, rect.top))
          || el.contains(efp(rect.right, rect.top))
          || el.contains(efp(rect.right, rect.bottom))
          || el.contains(efp(rect.left, rect.bottom))
      );
    };
    

    用法:

    import { isVisible } from '../utils';
    // ...
    const ele = document.getElementById(id);
    return isVisible(ele);
    

    逻辑并不复杂,不过多介绍。

    链接https://mp.weixin.qq.com/s/dYRCeLORlaiCzNgITniYZA

    相关文章

      网友评论

          本文标题:2021-01-06如何优雅的判断元素是否进入当前视区

          本文链接:https://www.haomeiwen.com/subject/zpknoktx.html