vue 監聽列表元素滾動到頁面可視區


 

下面看代碼吧

<template>
  <div>
    <ul class="ulBox" id="ulBox">
      <li class="li" :id="'id'+item" v-for="(item,index) in list" :key="index">
        {{item}}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
  data() {
    return {
      list: [1,2,3,4,5,6,7,8,9],
    };
  },
  created() {
  },
  mounted() {
    window.addEventListener('scroll', this.scrollToTop);
  },
  methods: {
    scrollToTop() {
      // 獲取視窗高度
      var domHight = document.body.offsetHeight;
      // dom滾動位置
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      // 獲取監聽元素
      var id;
      // 獲取監聽元素本身高度
      var scrollHeight;
      // 獲取監聽元素距離視窗頂部距離
      var offsetTop;
      // 獲取監聽元素距離頂部高度-窗口高度 
      var top;
      // 元素距離底部的高度+元素本身高度
      var bottom;
      this.list.map( (i) => {
        id = document.getElementById(`id${i}`);
        scrollHeight = id.scrollHeight;
        offsetTop = id.offsetTop;
        top = offsetTop - domHight > 0 ? offsetTop - domHight : 0;
        bottom = scrollHeight + offsetTop;
        // 頁面滾動位置 > 元素距離頂部高度-窗口高度 && 頁面滾動位置 < 元素距離頂部高度+元素本身高度
        if (scrollTop >= top && scrollTop <= bottom) {
          console.log('元素出現在可視區: ' + i);
        } else {
          console.log('元素不在了: ' + i);
        }
      });
    },
  },
}
</script>

<style lang='less' scoped>
  .ulBox {
    width: 100%;
    // height: 100vh;
    // overflow-y: scroll;
    margin: 0;
    padding: 0;
    list-style: none;
    .li {
      width: 100%;
      height: 5rem;
      border: 1px solid #999999;
      display: flex;
      justify-content: center;
      align-items: center;
    } 
    .li:not(:first-child) {
      border-top: none;
    }
  }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM