美文网首页
vue 监听滑动距离,显示回到顶部按钮

vue 监听滑动距离,显示回到顶部按钮

作者: 宇少_e010 | 来源:发表于2020-08-10 16:25 被阅读0次
<div class='button_boxlt'>
              <img src="../../images/回顶部@2x.png" alt="" v-show="toTopShow" @click="TopBotton">
  </div>
import { scrollAnimation } from "../../../static/scrolltop";
function scrollAnimation(currentY, targetY) {
  // 获取当前位置方法    600            0
  // const currentY = document.documentElement.scrollTop || document.body.scrollTop

  // 计算需要移动的距离
  let needScrollTop = targetY - currentY
  let _currentY = currentY
  setTimeout(() => {
    // 一次调用滑动帧数,每次调用会不一样
    const dist = Math.ceil(needScrollTop / 10)
    _currentY += dist
    window.scrollTo(_currentY, currentY)
    // 如果移动幅度小于十个像素,直接移动,否则递归调用,实现动画效果
    if (needScrollTop > 10 || needScrollTop < -10) {
      scrollAnimation(_currentY, targetY)
    } else {
      window.scrollTo(_currentY, targetY)
    }
  }, 1)
}
module.exports = {
  scrollAnimation
}
  mounted() {
    this.$nextTick(function() {
      //修改事件监听
      window.addEventListener("scroll", this.handleScroll);
    });
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
    TopBotton() {
      scrollAnimation(this.scrollTop, 0);
    },
    handleScroll() {
      this.scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (this.scrollTop > 300) {
        this.toTopShow = true;
      } else {
        this.toTopShow = false;
      }
    },

相关文章

网友评论

      本文标题:vue 监听滑动距离,显示回到顶部按钮

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