利用IntersectionObserver监听图片是否在当前视窗内

这篇博客详细介绍了如何利用Intersection Observer API来检测页面中元素的可视性状态。通过设置观察器选项,如root、rootMargin和threshold,当元素进入或离开视口时,可以动态地添加或移除特定样式类。示例代码展示了如何针对两个不同目标元素computerObserveTarget和bgCon2进行监控,根据intersectionRatio调整元素的视觉效果。
摘要由CSDN通过智能技术生成
created() {
    let options = {
      root: null,
      rootMargin: "0px",
      threshold: [0, 0.8],
    };
    this.intersectionObserver = new window.IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.target === this.computerObserveTarget) {
        /*isIntersecting (en-US) 的属性值来判断 target 元素在 root 元素中的可见性是否发生变化。如果 isIntersecting 为真,target 元素的至少已经达到 thresholds 属性值当中规定的其中一个阈值,如果为假,则 target 元素不在给定的阈值范围内可见*/
          if (entry.isIntersecting && entry.intersectionRatio > 0.7) {
            this.computerImage.classList.add("settled");
          } else if (!entry.isIntersecting && entry.intersectionRatio < 0.2) {
            this.computerImage.classList.remove("settled");
          }
        } else if (entry.target === this.bgCon2) {
          if (entry.isIntersecting && entry.intersectionRatio > 0.7) {
            this.samJZ.classList.add("settled");
          } else if (!entry.isIntersecting && entry.intersectionRatio <= 0.2) {
            this.samJZ.classList.remove("settled");
          }
        }
      });
    }, options);
  },
<div class="bg-con-2" v-element-init="initBgCon2"></div>
initBgCon2(element) {
      this.bgCon2 = element;
      this.intersectionObserver.observe(this.bgCon2);
    }
    ,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值