zoukankan      html  css  js  c++  java
  • 懒加载

     1.图片滚动到可视窗口区域后再进行加载

    index.html

    <img :data-src="subItem.thumbUrl" />
    

    index.js

    // imgonload这个方法在滚动监听中使用(可添加防抖),
    imgonload = () => {
        const img = document.querySelectorAll('img')
        for (let i = 0; i < img.length; i++) {
          if (img[i].getBoundingClientRect().top < window.innerHeight && !img[i].src) {
          // 图片一旦有src就会加载出来,所以图片的路径不会放在src中,而是一个自定义的属性data-src中
            img[i].src = img[i].dataset.src
          }
        }
      }
    

    getBoundingClientRect用于获取某个元素相对于视窗的位置集合。返回的结果是包含完整元素的最小矩形,并且拥有lefttoprightbottomxywidth, 和 height这几个以像素为单位的只读属性用于描述整个边框。除了width 和 height 以外的属性是相对于视图窗口的左上角来计算的。

    DOMRect 示例图

    当计算边界矩形时,会考虑视口区域(或其他可滚动元素)内的滚动操作,也就是说,当滚动位置发生了改变,top和left属性值就会随之立即发生变化(因此,它们的值是相对于视口的,而不是绝对的)。如果你需要获得相对于整个网页左上角定位的属性值,那么只要给top、left属性值加上当前的滚动位置(通过 window.scrollX 和 window.scrollY),这样就可以

    2.先加载一个缩略图,清晰图加载完毕后再进行替换

    index.html

    // thumbUrl是指缩略图的链接
    <img  id="load" :src="thumbUrl">

    index.js

    // thumbOriginal在获取到图片清晰图的链接后开始执行
    // calback可以不加 thumbOriginal = (originalUrl, callback) => { const load = document.getElementById('load') if (load && originalUrl) { const img = new Image()// 新建一个图片对象 img.src = originalUrl // 最终显示的大图 img.onload = () => { load.src = img.src callback&&callback() } } }

      

  • 相关阅读:
    Interesting Finds: 2008.10.27~2008.10.29
    Interesting Finds: 2008.11.21~2008.11.25
    Interesting Finds: 2008.11.31
    Interesting Finds: 2008.10.30~2008.10.31
    Interesting Finds: 2008.11.01~2008.11.07
    Interesting Finds: 2008.10.19~2008.10.23
    Interesting Finds: 2008.11.08~2008.11.11
    Interesting Finds: 2008.11.12~2008.11.14
    Interesting Finds: 2008.11.17~2008.11.18
    Interesting Finds: 2008.10.24~10.25
  • 原文地址:https://www.cnblogs.com/wangxirui/p/13398042.html
Copyright © 2011-2022 走看看