• js实现图片懒加载


    js实现图片懒加载

    1、介绍getBoundingClientRect()函数

    该函数没有参数,用于获取元素位置,返回一个对象,具有六个属性分别是:
    ele.getBoundingClientRect().top – 返回元素上边到视窗上边的距离
    ele.getBoundingClientRect().left – 返回元素左边到视窗左边的距离
    ele.getBoundingClientRect().bottom – 返回元素下边到视窗上边的距离
    ele.getBoundingClientRect().right – 返回元素右边到视窗左边的距离

    示例

    <style>
        div {
            position:relative;
            top: 50px;
            left: 50px;
            width: 100px;
            height: 120px;  
            border: 1px solid #000;                                                                                                
        }
    style>
    <div>
        啊啊啊啊啊啊啊啊
        啊啊啊啊啊啊啊啊
        啊啊啊啊啊啊啊啊
    div>
    <script>
         let div = document.querySelector("div");
         console.log("left:", div.getBoundingClientRect().left);
         console.log("right:", div.getBoundingClientRect().right);
         console.log("top:", div.getBoundingClientRect().top);
         console.log("bottom:", div.getBoundingClientRect().bottom);
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    控制台打印结果
    在这里插入图片描述

    实现图片懒加载

    将img的src属性值写进data-src中,监听页面滚动事件,当图片可以看见,也就是说img元素顶部距离视窗顶部距离小于视窗高度,则加载data-src中的图片路径,当img元素不能看见的时候,即img元素顶部距离视窗顶部距离小于视窗大小的时候,则不加载图片路径

    示例

    <img data-src="./logo.png" alt="">
    <img data-src="./logo.png" alt="">
    <img data-src="./logo.png" alt="">
        
    <script>
      const imgs = document.querySelectorAll('img');
      window.addEventListener('scroll', (e) => {
          imgs.forEach( img => {
              const imgTop = img.getBoundingClientRect().top;
              if(imgTop < window.innerHeight) {
                  const data_src = img.getAttribute('data-src');
                  img.setAttribute('src', data_src)
              }
          })
      })
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    但是以上方法有弊端,就是尽管图片已经加载完成,但依旧会不断的触发滚动事件
    因此推荐使用IntersectionObserver,这是浏览器提供的函数,交叉观察,当目标元素和可是窗口出现交叉区域时,触发事件事件会触发两次,目标元素看见和看不见都会触发

    IntersectionObserver

    <script>
    const imgs = document.querySelectorAll('img');
    const callback = (entries) => {
    	// 回调函数会接受一个entries参数
    	entries.forEach( entry => {
    		if(entry.isIntersecting) {  // 此属性进入交叉区就会为true,否则为false
    			const img= entry.target;  // 获取当前进入交叉区的元素
    			const data_src = img.getAttribute('data-src');
    			img.setAttribute('src', data_src);
    			observer.unobserve(img); // 加载完图片后对当前img元素停止观察
    		}
    	})
    }
    const observer = new IntersectionObserver(callback);
    
    imgs.forEach(img => {
    	observer.observe(img)
    })
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  • 相关阅读:
    用Python制造雪景图,体验 “ 人工下雪 ” 得快乐~
    C语言课程设计学生考勤管理系统
    视频超分之BasicVSR++阅读笔记
    Java实现计算两个日期之间的工作日天数
    通过ExecutorService、Callable、Future实现有返回结果的多线程来处理有轮询业务
    视频调整帧率、分辨率+音画同步
    【算法练习】LeetCode-2322. 从树中删除边的最小分数
    《机器人SLAM导航核心技术与实战》第1季:第6章_机器人底盘
    Python自学笔记11-函数的定义和调用
    第十章 项目管理基础知识
  • 原文地址:https://blog.csdn.net/weixin_42178670/article/details/127643509