vue 判断页面是否滚动到底部


需求

  • 要求用户阅读完本页所有内容后,下一步按钮才可以点击。

实现思路

  • 通过判断当前页面是否到达底部来设置按钮的点击事件。
  • 要判断当前页面是否到达底部需要用到三个距离——距离顶部的距离scrollTop、可视区域的高度clientHeight、滚动条的高度scrollHeight。

代码(在vue项目中使用)

mounted() {
    this.$nextTick(() => {
      // 进入nexTick
      const body: any = document.getElementById("app");   // 获取滚动条的dom
      // 获取距离顶部的距离
      const scrollTop = body.scrollTop;
      // 获取可视区的高度
      const windowHeight = body.clientHeight;
      // 获取滚动条的总高度
      const scrollHeight = body.scrollHeight;
      if (scrollTop + windowHeight >= scrollHeight) {
        // 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
        this.show = true
      } else {
        this.show = false;
        // 滚动事件
        body.onscroll = () => {
          console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
          if (scrollTop + windowHeight >= scrollHeight) {
            // 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
            this.show = true
          }
        }
      }
      console.log("距顶部" + scrollTop + "可视区高度" + windowHeight + "滚动条总高度" + scrollHeight);
    });
  }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM