1. 程式人生 > 實用技巧 >vue 監聽列表元素滾動到頁面可視區

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>