JS native implementation of lazy loading of images

Focus collection

<div class="box"> 
      <!-- 图片的src路径为空   lazyload="true"    data-original 值为真实的图片地址 -->
       <img src=""  class="img" lazyload="true" data-original="http://pic.58pic.com/58pic/17/18/97/01U58PIC4Xr_1024.jpg">
    </div>
<script type="text/javascript">
    window.onload = function () {
    
    
      //获取当前浏览器的视口高度
      var viewHeight = document.documentElement.clientHeight;
      console.log(viewHeight)
      //鼠标滚动回调
      function lazyload() {
    
    
          var img = document.getElementsByClassName('img'); //获取所有图片集合
          console.log(img)
          //遍历图片集合
          for (let item of img) {
    
    
              //获取图片距视口顶部的距离
              var imgHeight = item.getBoundingClientRect();
              //判断当图片出现在视口160px时把地址放到src中,显示出图片
              if (imgHeight.top < (viewHeight - 360)) {
    
    
                  item.src = item.getAttribute("data-original")
                   console.log(item.src)
              }
          }
      }

      lazyload();    //页面加载时把当前视口中的图片加载进来
      document.addEventListener('scroll', lazyload);
  }
  </script>

HTML data-*attributes

Use data-* attributes to embed custom data
All major browsers support data-* attribute
definitions and usage
data-* attributes are used to store private custom data for pages or applications.

The data-* attributes give us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can be used in the JavaScript of the page to create a better user experience (no Ajax calls or server-side database queries).

The data-* attribute consists of two parts:

The attribute name should not contain any uppercase letters, and there must be at least one character after the prefix "data-". The
attribute value can be any string.
Note: User agents will completely ignore custom attributes prefixed with "data-".

getBoundingClientRect Method introduction

Understanding: getBoundingClientRectUsed to obtain a collection of the position of an element relative to the window. There are top, right, bottom, left and other attributes in the collection.

1. Syntax: This method has no parameters.

        rectObject = object.getBoundingClientRect();

2. Return value type:

rectObject.top: the distance from the top of the element to the top of the window;

rectObject.right: the distance from the right of the element to the left of the window;

rectObject.bottom: the distance from the bottom of the element to the top of the window;

rectObject.left: the distance from the left side of the element to the left side of the window;

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_46034375/article/details/108736855