// scrollHeight滚动高度
function scrollToTop (y = 0, n = 8) {
if (typeof y !== 'number' && !isNaN(y)) {
return
}
var raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
(cb => setTimeout(cb, 1000 / 60))
var cRaf = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
var timer = null
var loop = () => {
var c = (document.documentElement.scrollTop || document.body.scrollTop) - y
if (Math.abs(c / n) < 1) {
scrollTo(0, y)
cRaf(timer)
timer = null
return
}
timer = raf(loop)
scrollTo(0, (document.documentElement.scrollTop || document.body.scrollTop) - c / n)
// setInterval计时器版本
// timer = setInterval(() => {
// var c = (document.documentElement.scrollTop || document.body.scrollTop) - y
// if (Math.abs(c / n) < 1) {
// scrollTo(0, y)
// cRaf(timer)
// timer = null
// return
// }
// scrollTo(0, (document.documentElement.scrollTop || document.body.scrollTop) - c / n)
// }, 1000 / 60)
}
return loop()
}
function scrollToElement (el, n = 8) {
var y = el.offsetTop
var raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
(cb => window.setTimeout(cb, 1000 / 60))
var cRaf = window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
window.clearTimeout
var timer = null
var loop = () => {
var c = (document.documentElement.scrollTop || document.body.scrollTop) - y
if (Math.abs(c / n) < 1) {
scrollTo(0, y)
cRaf(timer)
timer = null
return
}
timer = raf(loop)
scrollTo(0, (document.documentElement.scrollTop || document.body.scrollTop) - c / n)
// setInterval计时器版本
// timer = setInterval(() => {
// var c = (document.documentElement.scrollTop || document.body.scrollTop) - y
// if (Math.abs(c / n) < 1) {
// scrollTo(0, y)
// cRaf(timer)
// timer = null
// return
// }
// scrollTo(0, (document.documentElement.scrollTop || document.body.scrollTop) - c / n)
// }, 1000 / 60)
}
return loop()
}
console