原生JS基于window.scrollTo()封装垂直滚动动画工具函数

概要:
原生JS基于window.scrollTo()封装垂直滚动动画工具函数,可应用与锚点定位、回到顶部等操作。

封装原因:

在vue项目中,遇到需要实现垂直滚动效果的需求,初步想到的方法有两个:
1:使用window.scrollTo()方法,但是这个方法是没有动画效果的,需要手动封装一下。
2:使用JQuery的动画函数,缺点比较明显:需要引入JQuery。
显然,选择第一种好很多。

以下为封装window.scrollTo()的方法scroll(),文件名为scroll.js

// Created by xiaoqiang on 30/05/2018.
/**
 * @param {numeber} currentY 需要移动的dom当前位置离网页顶端的距离
 * @param {number} targetY 需要移动的dom当前位置离要移到的位置的距离
 */
function scroll (currentY, targetY) {
  // 计算需要移动的距离
  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) {
      scroll(_currentY, targetY)
    } else {
      window.scrollTo(_currentY, targetY)
    }
  }, 1)
}
// 暴露此方法
export default scroll

使用方法

比如在vue中,可以这样用:
import scroll form '@/common/util/scroll.js'
引入方法。
在响应触发事件的函数中调用scroll(),需要传入两个参数,比如:

  methods: {
    test () {
      const scrollHeight = document.getElementsByClassName('scroll-element')[0].offsetTop
      const currentY = document.documentElement.scrollTop || document.body.scrollTop
      scroll(currentY, scrollHeight)
    }
  }

有错误或不清晰或可以改进的地方欢迎指出,O(∩_∩)O~~

猜你喜欢

转载自blog.csdn.net/fabulous1111/article/details/80504137
今日推荐