zoukankan      html  css  js  c++  java
  • 编写代码实现图片懒加载

    <!DOCTYPE html>
      <html>
        <head>
          <title>图片的懒加载</title>
          <style>
          * {
            margin: 0;
            padding: 0;
           }
          .container {
            margin:0 auto;
             800px;
          }
          .imgBox {
            height: 430px;
            margin-bottom: 20px;
            overflow: hidden;
            background-color: #eee;
          }
          .imgBox img {
            display: none;
             100%;
          }
         </style>
        </head>
        <body>
          <div class="container">
            <!-- <div class="imgBox"><img src="" alt="" data-img="./images/111.jpg"></div> -->
          </div>
          <script src="node_modules/jquery/dist/jquery.min.js"></script>
          <script src="DelayImg.js"></script>
        </body>
      </html>
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     
    let $container = $('.container'),
      $imgBoxs = null,
        $window = $(window);

    // => 造点假数据 new Array(20).fill(null) 创建长度为20的数组,每项用 null 填充
    let str = ``;
    new Array(20).fill(null).forEach(item => {
      str += `<div class="imgBox"><img src="" alt="" data-img="./images/111.jpg"></div>`;
    });
    $container.html(str);
    $imgBoxs = $container.children('.imgBox');

    // => 多张图片延迟加载
    $window.on('load scroll', function () {
      // => $B 获取浏览器底边框距离 body 的距离
      let $B = $window.outerHeight() + $window.scrollTop();
      // => 循环每一个图片区域,根据自己区域距离 body 的距离,计算出里面的图片是否加载
      $imgBoxs.each((index, item) => {
        let $item = $(item);
        $itemA = $item.outerHeight() + $item.offset().top,
        isLoad = $item.attr('isLoad');
        if ($itemA <= $B && isLoad !== 'true') {
          $item.attr('isLoad', true);
          // => 加载当前区域中的图片
          let $img = $item.children('img');
          $img.attr('src', $img.attr('data-img'));
          $img.on('load', () => $img.stop().fadeIn());
        }
      });
    })



  • 相关阅读:
    paip.提升效率僵尸代码的迷思
    paip.输入法编程词库多意义条目分割 python实现.
    paip.提升效率提升绑定层次form绑定取代field绑定
    paip.提升效率调试日志系统日志参数含义python
    paip.自定义java 泛型类与泛型方法的实现总结
    paip.提升效率request自动绑定domain object
    paip.提升效率filter map reduce 的java 函数式编程实现
    paip.php 5.0 5.3 5.4 5.5 6.0的新特性总结与比较
    paip.解决中文url路径的问题图片文件不能显示
    paip.判断字符是否中文与以及判读是否是汉字uapi python java php
  • 原文地址:https://www.cnblogs.com/HYTing/p/12615964.html
Copyright © 2011-2022 走看看