v2 img lazy

adong搬砖發表於2024-04-21
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<script src="../v2原始碼探究/v2原始碼js"></script>
<style>
  * {
    margin: 0;
    padding: 0;
  }

  html,
  body {
    height: 100%;
    overflow: auto;
    padding-top: 1000px;
  }
</style>

<body>
  <div class="app">
    <img src="" alt="" v-my style="height: 800px;width: 600px;" data-src="../1684739840420.jpg">
  </div>
  <script>
    new Vue({
      el: ".app",
      methods: {},
      directives: {
        my: {
          inserted (el) {
            const ob = new IntersectionObserver((entries) => {
              const el = entries[0].target
              if (entries[0].isIntersecting) {
                ob.unobserve(el)
                el.src = el.dataset.src
              }
            }, { threshold: 0.5 })
            ob.observe(el)
          }
        }
      }
    })
  </script>
</body>

</html>

相關文章