前端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);
  },
相关推荐
智码看视界30 分钟前
老梁聊全栈系列:(阶段一)架构思维与全局观
java·javascript·架构
小周同学@2 小时前
谈谈对this的理解
开发语言·前端·javascript
Wiktok2 小时前
Pyside6加载本地html文件并实现与Javascript进行通信
前端·javascript·html·pyside6
一只小风华~2 小时前
Vue:条件渲染 (Conditional Rendering)
前端·javascript·vue.js·typescript·前端框架
柯南二号2 小时前
【大前端】前端生成二维码
前端·二维码
程序员码歌3 小时前
明年35岁了,如何破局?说说心里话
android·前端·后端
博客zhu虎康3 小时前
React Hooks 报错?一招解决useState问题
前端·javascript·react.js
灰海4 小时前
vue中通过heatmap.js实现热力图(多个热力点)热区展示(带鼠标移入弹窗)
前端·javascript·vue.js·heatmap·heatmapjs
王源骏4 小时前
LayaAir鼠标(手指)控制相机旋转,限制角度
前端
大虾写代码4 小时前
vue3+TS项目配置Eslint+prettier+husky语法校验
前端·vue·eslint