JS监听DOM元素滚动

使用监听 scroll 可以实现监听页面滚动或者元素滚动是否到底

// 获取需要监听滚动的DOM元素
const element = document.getElementById('your-element-id');

// 监听滚动事件
element.addEventListener('scroll', function() {
  // 判断是否滚动到页面底部
  if (element.scrollHeight - element.scrollTop === element.clientHeight) {
    console.log('已滚动到页面底部');
    // 在这里执行你的操作
  }
});

在vue中的示例:

<template>
  <div class="app-container">
    <div class="box">
      <div v-for="(item,index) in count" :key="index" class="item">
        {
   
   { item }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {

    }
  },
  mounted() {
     this.$nextTick(()=>{
        this.handlerNodeScroll()
     })
  },
  methods: {
    // 监听元素滚动
    handlerNodeScroll() {
      let that = this
      // 函数防抖
      let fun = that.debounce(e => {
        // 距顶部
        let scrollTop = e.target.scrollTop;
        // 可视区高度
        let clientHeight = e.target.clientHeight;
        // 滚动条总高度
        let scrollHeight = e.target.scrollHeight;
        // 如果当前距离顶部的值加上可视区域的值大于等于总高度,则任务滚动条触底
        if (scrollTop + clientHeight >= scrollHeight) {  
          console.log('滚动到底部');
     
        }
      }, 50)
      
      // 监听滚动
      let box = document.querySelector(".box");
      box.addEventListener("scroll",  (e)=> {
        fun(e)
      })
    },
    // 函数防抖
    debounce(handle, delay) {
      let timer = null;
      return function () {
        let _self = this,
          _args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          handle.apply(_self, _args)
        }, delay)
      }
    }
  }
}
</script>


猜你喜欢

转载自blog.csdn.net/qq_29483485/article/details/131172913