• 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
  • 相关阅读:
    记录--CSS 滚动驱动动画 scroll()
    STM32F4-TFT-SPI时序逻辑分析仪调试记录
    自动驾驶中的人工智能,自动驾驶与人工驾驶
    Spring
    【软件测试】03 -- 软件测试概述
    Day716. 抛出异常是一个合适的选择吗? -Java8后最重要新特性
    ajax 中 success 方法的 return
    数据库的下一个变革方向——云原生数据库
    find_first_of()函数和find_last_of()函数
    CentOS7开机启动 jar包
  • 原文地址:https://blog.csdn.net/weixin_44582045/article/details/134281310