前端Vue 页面滑动监听 拿到滑动的坐标值

前言

前端Vue 页面滑动监听 拿到滑动的坐标值

实现

Vue2写法

js 复制代码
  mounted() {
    // 监听页面滚动事件
    window.addEventListener("scroll", this.scrolling);

  },
methods: {
scrolling() {
      // 滚动条距文档顶部的距离
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      // 滚动条滚动的距离
      let scrollStep = scrollTop - this.oldScrollTop;
      console.log("header 滚动距离 ", scrollTop);
      // 更新------滚动前,滚动条距文档顶部的距离
      this.oldScrollTop = scrollTop;

      //变量windowHeight是可视区的高度
      let windowHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      //变量scrollHeight是滚动条的总高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

      //滚动条到底部的条件
      if (scrollTop + windowHeight == scrollHeight) {
        //你想做的事情
        console.log("header  你已经到底部了");
      }
      if (scrollStep < 0) {
        console.log("header 滚动条向上滚动了!");
      } else {
        console.log("header  滚动条向下滚动了!");
      }
      // 判断是否到了最顶部
      if (scrollTop <= 0) {
        console.log("header 到了最顶部")
      } 
    },

},
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrolling);
  },
相关推荐
mapbar_front5 分钟前
我们需要前端架构师这个职位吗?
前端
ScriptBIN13 分钟前
Javaweb--Vue
前端·vue.js
KenXu18 分钟前
React Conf 2025 - 核心更新
前端
前端Hardy22 分钟前
Vue 高效开发技巧合集:10 个实用技巧让代码简洁 50%+,面试直接加分!
前端·javascript·vue.js
ᖰ・◡・ᖳ43 分钟前
JavaScript:神奇的ES6之旅
前端·javascript·学习·es6
app出海创收老李1 小时前
海外独立创收日记(5)-上个月收入回顾与本月计划
前端·后端·程序员
前端Hardy1 小时前
HTML&CSS:一眼心动的 SVG 时钟
前端·javascript·css
TTGGGFF1 小时前
Streamlit:CSS——从基础到实战美化应用
前端·css
app出海创收老李1 小时前
海外独立创收日记(4)-第一笔汇款
前端·后端·程序员
Takklin1 小时前
React JSX 转换原理与 GSR 实现解析
前端·react.js