1. 程式人生 > >原生js實現window.scrollTo()滾動動畫

原生js實現window.scrollTo()滾動動畫

在vue專案中要使用到,

  • 適用於滾動到頂部,
  • 滾動到指定位置
/**
 * 動畫垂直滾動到頁面指定位置
 * @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) } module.exports = { scrollAnimation }

使用方法

import { scrollAnimation } from '../../static/js/utils.js';

const currentY = document.documentElement.scrollTop || document.body.scrollTop
scrollAnimation(currentY, 0)

效果預覽這裡寫圖片描述