• 编写代码实现图片懒加载


    <!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());
        }
      });
    })



  • 相关阅读:
    HDU 4388 To the moon
    HDU 4757 Tree
    HDU 5816 Hearthstone
    hihocoder 1356 分隔相同整数
    HDU 5726 GCD
    POJ3026 Borg Maze(Prim)(BFS)
    POJ1258 Agri-Net(Prim)
    POJ1751 Highways(Prim)
    POJ2349 Arctic Network(Prim)
    POJ1789 Truck History(Prim)
  • 原文地址:https://www.cnblogs.com/HYTing/p/12615964.html
Copyright © 2020-2023  润新知