scrollTo滚动效果

Posted 亲爱的阿乾

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了scrollTo滚动效果相关的知识,希望对你有一定的参考价值。

Math.easeInOutQuad = function (t, b, c, d) {
  t /= d / 2
  if (t < 1) {
    return c / 2 * t * t + b
  }
  t--
  return -c / 2 * (t * (t - 2) - 1) + b
}

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function () {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60) }
})()

/**
 * Because it\'s so fucking difficult to detect the scrolling element, just move them all
 * @param {number} amount
 */
function move(amount, domTarget) {
  if (domTarget && document.querySelector(domTarget)) {
    document.querySelector(domTarget).scrollTop = amount
  } else if (document.querySelector(\'.base\')) {
    document.querySelector(\'.base\').scrollTop = amount
  }
  document.documentElement.scrollTop = amount
  document.body.parentNode.scrollTop = amount
  document.body.scrollTop = amount
}

function position(domTarget) {
  if (domTarget && document.querySelector(domTarget)) {
    return document.querySelector(domTarget).scrollTop || document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
  }
  return document.querySelector(\'.base\') && document.querySelector(\'.base\').scrollTop || document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop
}

/**
 * @param {number} to
 * @param {number} duration
 * @param {Function} callback
 */
export function scrollTo(to, duration, callback, domTarget) {
  const start = position(domTarget)
  const change = to - start
  const increment = 20
  let currentTime = 0
  duration = (typeof (duration) === \'undefined\') ? 500 : duration
  var animateScroll = function () {
    // increment the time
    currentTime += increment
    // find the value with the quadratic in-out easing function
    var val = Math.easeInOutQuad(currentTime, start, change, duration)
    // move the document.body
    move(val, domTarget)
    // do the animation unless its over
    if (currentTime < duration) {
      requestAnimFrame(animateScroll)
    } else {
      if (callback && typeof (callback) === \'function\') {
        // the animation is done so lets callback
        callback()
      }
    }
  }
  animateScroll()
}


// 代码中使用
// import { scrollTo } from "Tools/scroll-to";
// scrollTo(0, 1600, \'\', \'.target\');

以上是关于scrollTo滚动效果的主要内容,如果未能解决你的问题,请参考以下文章

JS操作滚动条置顶+动画效果

JS操作滚动条置顶+动画效果

Android ScrollView在滚动中调用scrollTo(0,0)回到顶部无效

如何使用 JQuery $.scrollTo() 函数滚动窗口

Cypress web自动化30-操作窗口滚动条(scrollTo)

Cypress web自动化30-操作窗口滚动条(scrollTo)