js判断元素出现在可视区域/图片懒加载实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img {
      display: block;
      width: 200px;
      height: 200px;
    }
  </style>
</head>

<body>
  <div class="box">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
    <img class="my-photo" alt="loading" data-src="./img/logo.png">
  </div>

  <script>
    window.onload = function () {
      const io = new IntersectionObserver(ios => {
        ios.forEach(item => {
          const el = item.target
          if (item.intersectionRatio > 0 && item.intersectionRatio <= 1) {
            loadImg(el)
            io.unobserve(el)
          }
          el.onload = el.onerror = () => io.unobserve(el)
        })
      })

      checkImg()
      window.onscroll = function () { checkImg() }

      function loadImg (el) {
        el.src = el.dataset.src
      }

      function checkImg () {
        const imgs = document.querySelectorAll('.my-photo')
        Array.from(imgs).forEach(item => {
          if (isInviewThree(item)) {
            loadImg(el)
          }
        })
      }


      //检测方法1
      function isInviewOne (el) {
        const viewH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
        const scrollTop = document.documentElement.scrollTop
        return el.offsetTop - scrollTop <= viewH + 50
      }
      //检测方法2
      function isInviewTwo (el) {
        const viewH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
        const elTop = el.getBoundingClientRect().top
        return elTop <= viewH + 50
      }
      //检测方法3
      function isInviewThree (el) {
        io.observe(el)
      }

    }
  </script>
</body>

</html>
posted @ 2022-08-23 15:31  Samsara315  阅读(233)  评论(0编辑  收藏  举报