设置某一带有滚动条的DOM元素从现有位置滚动至指定位置(过渡效果)

前言:

        自用

代码实现:(简易版)

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
}
function move(targetHTML, val) {
  targetHTML.scrollTop = val
}
function scroll(targetHTML, targetPosition) {
  let start = targetHTML.scrollTop //开始位置
  let change = targetPosition - start
  const increment = 20
  const duration = 500
  let currentTime = 0
  let animateScroll = function () {
    currentTime += increment
    let distance = Math.easeInOutQuad(currentTime, start, change, duration)
    move(targetHTML, distance)
    if (currentTime < duration) {
      requestAnimationFrame(animateScroll)
    }
  }
  animateScroll()
}
//使用
function goTop() {
   //指定元素,和要滚至的位置
  scroll(document.querySelector('.user_container'), 0)
}

 若依系统:(代码是设置window的滚动条)

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
}

var requestAnimFrame = (function() {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60) }
})()

function move(amount) {
  document.documentElement.scrollTop = amount
  document.body.parentNode.scrollTop = amount
  document.body.scrollTop = amount
}

function position() {
  return 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) {
  const start = position()
  const change = to - start
  const increment = 20
  let currentTime = 0
  duration = (typeof (duration) === 'undefined') ? 500 : duration
  var animateScroll = function() {
    currentTime += increment
    var val = Math.easeInOutQuad(currentTime, start, change, duration)
    move(val)
    if (currentTime < duration) {
      requestAnimFrame(animateScroll)
    } else {
      if (callback && typeof (callback) === 'function') {
        callback()
      }
    }
  }
  animateScroll()
}

猜你喜欢

转载自blog.csdn.net/m0_73334325/article/details/134832966