weixin_57909439 2022-11-14 23:30 采纳率: 85%
浏览 5
已结题

我想要实现图片懒加载,用getBoundingClientRect()获得相对于视口的位置 这个img的src应该为空才对,因为这张图片的位置处于视口外,可是它现在的src不是为空

我想要实现图片懒加载,用getBoundingClientRect()获得相对于视口的位置

这个img的src应该为空才对,因为这张图片的位置处于视口外,可是它现在的src不是为空

img

img

在没有滑动滚动条的情况下
第一个数是图片的getBoundingClientRect().top
第二个数是视图的高

img

在滑动滚动条后,把滚动条滑到顶部,图片的getBoundingClientRect().top变正常了

img


这究竟是为什么??


        let imgs = document.querySelectorAll('img')
        fn()
        window.onscroll = lazyload
        function fn(){
            let clientH = window.innerHeight 
            Array.from(imgs).forEach((item,index)=>{
                let oBounding = item.getBoundingClientRect()
                console.log(oBounding.top,clientH)
                if(oBounding.top>0 && oBounding.top <= clientH ){
                    item.src = item.getAttribute('data-url')
                }
            })
        }
        let flat = true
        function lazyload(){
            if(flat){
                flat = false
                setTimeout(function(){
                    fn()
                    flat = true
                },300)
            }else{
                return
            }            
        }
  • 写回答

1条回答 默认 最新

  • 这个需求做不了123 2022-11-15 10:17
    关注

    单纯看你上面的代码没发现有什么问题,我前两天也实现了这个功能,也有用到这个,我是这样写的

    <template>
          <div>
            <img v-for="(item,i) in lazyImgs" style="width: 180px;height:240px;margin- 
              top:40px;display: inline-block;" :data-src="item"  :key="i" src="" v-lazy  
            alt="">
          </div>
    </template>
    
    async mounted() {
        window.addEventListener("scroll", (e) => {
          // 这里做一个 节流 操作
          if (this.timer) return;
          this.timer = setTimeout(() => {
            this.query("img[data-src]").forEach((img) => {
              const rect = img.getBoundingClientRect();
              if (rect.top < window.innerHeight) {
                img.src = img.dataset.src;
                // 我们是通过img[data-src]查找所有img标签的,渲染后就删除data-src可减少forEach循环的计算成本
                img.removeAttribute("data-src"); 
              }
            });
            clearTimeout(this.timer);
            // 这里一定要把定时器置为 null
            this.timer = null
          }, 300);
        });
    }
    
    

    你可以参考一下,另外我还用观察器实现了一版,可以进我主页博客看下,拿来就能用,没有问题

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月23日
  • 已采纳回答 11月15日
  • 创建了问题 11月14日

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么