木木哒 发表于 6 天前

使用IntersectionObserver 实现:自动监听元素是否进入了设备的可视区域之

IntersectionObserver (自动监听元素是否进入了设备的可视区域之内)

示例:
const io = new IntersectionObserver(callback, option);

// 获取元素
const target = document.getElementById("dom");
// 开始观察
io.observe(target);

// 停止观察
io.unobserve(target);

// 关闭观察器
io.disconnect();vue示例:
const className = 'enterpage';

const directives = {
viewport: {
    inserted: function (el, binding, vnode) {
      // 设置观察器选项
      const options = {
      root: null, // 使用视窗作为根
      rootMargin: '0px', // 根边界盒与目标边界盒之间的边距
      threshold: 0.4 // 交叉比例(即目标元素的可见区域占比)
      };

      // 创建一个新的 Intersection Observer 实例
      const observer = new IntersectionObserver((entries, observer) => {
      // 遍历所有观察目标的条目
      entries.forEach((entry) => {
          // 如果目标元素的交叉比例大于 0(即部分可见)
          if (entry.isIntersecting) {
            console.log('可见了');
            // 添加 class
            el.classList.add(className);
          }
      });
      }, options);

      // 使用观察器观察目标元素
      observer.observe(el);

      // 组件销毁时停止观察
      vnode.context.$once('hook:beforeDestroy', function () {
      observer.unobserve(el);
      });
    },
    unbind(el) {
      // 移除 class
      el.classList.remove(className);
    }
}
};

export default directives;上面示例表示,当某个元素进入到可视范围内,给当前元素添加一个类名,这个类名可以给当前元素添加一些动画效果之类的。

来源:https://www.cnblogs.com/moqiutao/p/18412877
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 使用IntersectionObserver 实现:自动监听元素是否进入了设备的可视区域之