做了小东西,一个辅助阅读文章的小功能

主要是手机端来用的

废话不多说

拆分两部分

/**
* 单击事件自动向上或向下滚动一屏
*/
function paging(e) {
    //获取鼠标位置(相对于浏览器)
    var x = event.clientY;
    //获取窗口高度
    var h = window.innerHeight;
    //获取当前位置
    var c = document.body.scrollTop;
    //计算滚动距离
    var t = x > (h / 2) ? h : -h;
    //开滚
    scrollAnimation(c, c + t);
}
/**
 * 动画垂直滚动到页面指定位置
 * @param { Number } currentY 当前位置
 * @param { Number } targetY 目标位置
 */
function scrollAnimation(currentY, targetY) {
  // 获取当前位置方法
  // 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)
}

 

Last modification:May 5, 2022
如果觉得我的文章对你有用,请随意赞赏