• IntersectionObserver的使用


    一、前言

    IntersectionObserver 是一个现代浏览器提供的 API,用于监听元素与其祖先元素或顶层文档视窗(viewport)交叉的情况,即元素是否进入或离开视窗。

    它通常用于实现懒加载图片、监听滚动事件、触发动画效果等场景,可以显著提高性能和用户体验。

    二、基本用法

    创建 Intersection Observer 实例

    const options = {
      root: null, // 根元素,默认是视窗   填要观察元素的父级
      rootMargin: '0px', // 根元素的边距
      threshold: 0.5 // 当目标元素 50% 进入视窗时触发回调
    }
    const observer = new IntersectionObserver(callback, options)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    指定观察目标:

    const target = document.querySelector('.target-element')
    observer.observe(target)
    
    • 1
    • 2

    编写回调函数:

    function callback(entries, observer) {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 目标元素进入视窗
          console.log('目标元素进入视窗')
          // observer.unobserve(target) // 假如是懒加载图片  完成加载就不用去监听了 
        } else {
          // 目标元素离开视窗
          console.log('目标元素离开视窗')
        }
      })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    停止观察:

    observer.unobserve(target)
    
    • 1

    关闭观察器:

    observer.disconnect()
    
    • 1

    三、例子

    1、进入视窗改变背景色

    <!DOCTYPE html>
    <html>
    <head>
      <title>Intersection Observer 示例</title>
    </head>
    <body>
      <div class="target-element" style="height: 200px; background-color: lightblue;">
        目标元素
      </div>
    
      <script>
        // 创建 Intersection Observer 实例
        const options = {
          root: null, // 根元素,默认是视窗
          rootMargin: '0px', // 根元素的边距
          threshold: 0.5 // 当目标元素 50% 进入视窗时触发回调
        };
    
        const observer = new IntersectionObserver(callback, options);
    
        // 获取目标元素
        const target = document.querySelector('.target-element');
    
        // 指定观察目标
        observer.observe(target);
    
        // 编写回调函数
        function callback(entries, observer) {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              // 目标元素进入视窗
              console.log('目标元素进入视窗');
              target.style.backgroundColor = 'lightgreen'; // 改变背景颜色
            } else {
              // 目标元素离开视窗
              console.log('目标元素离开视窗');
              target.style.backgroundColor = 'lightblue'; // 恢复原始背景颜色
            }
          });
        }
      </script>
    </body>
    </html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    2、视频广告要完全进入视窗才能播放,不然暂停

    在这里插入图片描述

    const ob = new IntersectionObserver((entries) => {
    	const entry = entries[0]
    	const vdo = entry.target
    	if (entry.isIntersecting) {
    		vdo.play()
    	} else {
    		vdo.pause()
    	}
    }, {
    	threshold: 1
    })
    
    ob.observe(document.querySelector('video'))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    java - 包装类
    【发布】DDD 工程脚手架 + 一键安装分布式技术栈环境!
    QT基础入门——认识与创建QT(一)
    UVA 10050【埃筛】【set】
    吃透这份高并发/调优/分布式等350道面试宝典,已涨30k
    docker网络模式、资源控制
    android service基本介绍
    ES9,ES10
    推荐系统类别特征的embedding
    Win系统服务器管理器打开方式
  • 原文地址:https://blog.csdn.net/weixin_44582045/article/details/134281310