美文网首页
3、vue 实时监听窗口滚动条

3、vue 实时监听窗口滚动条

作者: 郑先森 | 来源:发表于2020-12-16 16:08 被阅读0次

    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)
      }
    

    获取总高度

    var viewportSize = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
    console.log(viewportSize)
    

    [JS如何判断滚动条是否滚到底部]

    判断滚动条到底部,需要用到DOM的三个属性值,即scrollTop、clientHeight、scrollHeight。

    scrollTop为滚动条在Y轴上的滚动距离。

    clientHeight为内容可视区域的高度。

    scrollHeight为内容可视区域的高度加上溢出(滚动)的距离。

    从这个三个属性的介绍就可以看出来,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。

    代码如下(兼容不同的浏览器)。

    <pre style="overflow: auto; margin-top: 0px; margin-bottom: 0px;">
    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    

    避免没有数据的时候 重复执行 scrollHeight > clientHeight </pre>

    <pre style="overflow: auto; margin-top: 0px; margin-bottom: 0px;">if(scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
     this.loadmore();
    }</pre>
    

    加这个就能显示了
    window.onresize = () => {
    return (() => {
    })()
    }

    相关文章

      网友评论

          本文标题:3、vue 实时监听窗口滚动条

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