美文网首页
vue 监听滚动条事件

vue 监听滚动条事件

作者: chan_it | 来源:发表于2019-08-16 15:36 被阅读0次

vue 中滚轮滚动监听事件

方式一:
<script>
export default {
  data () {
    return {
      // 滚动条的高度
      scrollTop: 0
    }
  },

  methods: {
    // 保存滚动值,这是兼容的写法
    handleScroll () {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    },

    // 滚动条回到顶部
    backTop () {
      if (this.scrollTop > 10) {
        document.documentElement.scrollTop = 0
      }
    }
  },

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

  destroyed () {
    // 离开该页面需要移除这个监听的事件,不然会报错
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
方式一:
<div  ref="Box"  style="overflow: scroll;"></div>

mounted(){
  // 先给页面注册滚动事件
  document.addEventListener('scroll',this.Scroll, true)
}

methods: {
  // 滚动事件,绑定到元素div块
  // 如果不绑定到元素上,则只能监听页面滚动
  Scroll(){
    console.log(this.$refs.orderBox.scrollTop)
 }
}

// 将指定设有scroll的盒子滚动到顶部
this.$refs.Box.scrollTop = 0 ;

注意:

  1. addEventListener事件要加 true 。
  2. 如果页面设置了 overflow:hidden ,则监测到的滚动值一直是0,注意页面的css overflow的影响,改为 overflow: visible或者其它。
  3. 方式二参考:https://blog.csdn.net/qq_36990322/article/details/83823933

相关文章

网友评论

      本文标题:vue 监听滚动条事件

      本文链接:https://www.haomeiwen.com/subject/sffolctx.html