图片懒加载

85 阅读1分钟

这是一个拖了很久的想实现的功能(鄙人较菜,研究参考别人的实现方法半年,到现在才算实现) 唉,还是对时间把握不够好,要改改自己的坏毛病

下面这实现方式集百家之智慧,记录一下

属性概念

<style>
*{
  margin: 0;
  padding: 0;
}
.boxS{
  margin: 4px;
  border:20px solid #000;
  padding:5px;
  height:1000px;
  background: pink;
}
.boxT{
  margin: 8px;
  border:6px solid #000;
  padding:3px;
  height:23px;
  background: skyblue;
}
#appS{
  margin:10px;
  border:1px solid #999;
  padding: 15px;
  height:500px;
  overflow-y:auto;
  background: orange;
}
</style>

<body>
    <div id="appS">
      <div class="boxS"></div>
      <div class="boxT"></div>
    </div>
</body>

<script>
    const boxS = document.querySelector('.boxS');
    const appS = document.querySelector('#appS');
    const boxT = document.querySelector('.boxT');
</script>

offsetxxx

offsetHeight/offsetWidth/offsetTop

  • box-sizing:content-box
console.log(boxS.offsetHeight) // 20+5+1000+5+20 => 1050
console.log(boxT.offsetHeight) // 6+3+23+3+6 => 41
console.log(appS.offsetHeight) // 1+15+500+15+1 =>532
// 结论
// 不计算margin
console.log(boxS.offsetTop) // 10+1+15+4 =>30
console.log(boxT.offsetTop) // 10+1+15+4+20+5+1000+5+20+8 => 1088
console.log(appS.offsetTop) // 10 
// 结论
// 页面顶部到实际内容的距离

clientxxx

clientHeight/clientWidth

  • box-sizing:content-box
console.log(boxS.clientHeight) // 5+1000+5 => 1010
console.log(boxT.clientHeight) // 3+23+3 => 29
console.log(appS.clientHeight) // 15+500+15 => 530 
// 结论
// 页面内容区域 padding+content

scrollxxx

scrollHeight/scrollWidth

  • box-sizing:content-box
// scroll存在 => 15+4+20+5+1000+5+20+4+15
console.log(appS.scrollHeight) // 15+4+20+5+1000+5+20+8+6+3+23+3+6+8+15 => 1141

// scroll不存在 => content+padding => clientHeight
console.log(boxS.scrollHeight) // 5+1000+5 => 1010
console.log(boxT.scrollHeight) // 3+23+3 => 29

scrollTop

  1. 外部div需要有一定的高度
  2. 内部的div的高度要大于外部div的高度
  3. 外部div设置overflow,这样给外部设置scrollTop才会生效
app.addEventListener('scroll',() => {
    console.log(appS.scrollTop)
})

image.png

image.png

getBoundingClientRect()

文档链接

作用:用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。

实例

思路:把图片路径存放在自定义属性里面,当图片滚动至展示区域时,将自定义的属性值赋值给src属性

<body>
  <div class="box">
    <img data-src="./01.png" alt="" srcset="">
    <img data-src="./02.png" alt="" srcset="">
    <img data-src="./03.png" alt="" srcset="">
  </div>

  <script>
    let Img = document.querySelectorAll('img');
    let box = document.querySelector('.box');
    let bottomHeight = box.offsetTop + box.offsetHeight; // 底部距离

    function show() {
      Img.forEach((item) => {
        if (item.getBoundingClientRect().top < bottomHeight){
        // 当图片的顶部小于显示框的最底部距离,即为要出现在展示区域内
          item.setAttribute('src',item.dataset.src)
        }
      })
    }
    show();

    box.addEventListener('scroll',show)
  </script>
</body>