欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue 监听滚动条

程序员文章站 2022-06-17 17:21:01
一、事件绑定到页面1.在 mounted 生命周期函数注册滚动条事件mounted() { window.addEventListener('scroll', this.windowScroll)}2.在 methods 方法里使用methods: { windowScroll() { // 滚动条距离页面顶部的距离 let scrollTop = window.pageYOffset || document.documentElement.scrollTop ||...

一、事件绑定到页面

1.在 mounted 生命周期函数注册滚动条事件

mounted() {
  window.addEventListener('scroll', this.windowScroll)
}

2.在 methods 方法里使用

methods: {
  windowScroll() {
     // 滚动条距离页面顶部的距离
     let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      console.log(scrollTop);
  }
}

3.销毁组件前解绑事件

  beforeDestroy() {
 	 window.removeEventListener('scroll', this.windowScroll)
  }

二、绑定到局部div内

1.标签绑定事件

<div ref="Box" @scroll="divScroll"></div>

2.在 methods 方法里使用

methods: {
  divScroll(e) {
    const sh = this.$refs.Box.scrollHeight
    const ch = this.$refs.Box.clientHeight
    const st = this.$refs.Box.scrollTop
    console.log('滚动条高度' + sh)
    console.log('可视区高度' + ch)
    console.log('距离顶部距离' + st)
    if (ch + st== sh) {
      console.log('到底啦...')
    }
  },
}

本文地址:https://blog.csdn.net/qq_36441761/article/details/111932729

相关标签: vue vue.js