【JavaScript】浏览器中平滑位移到指定选择器元素的位置
2018-11-13 本文已影响0人
burningalive
参数填选择器即可, 比如用于回到顶部时只需要ele.addEventListener(moveTo('body'));
function moveTo (sel) {
const tar = document.querySelector(sel)
if (tar) {
let doc = document
// 不传入参数时返回当前浏览器scrollTop值, 传入参数时先设置当前页面scrollTop值再返回设置后的scrollTop值
const docTop = function (...arg) {
if (arg.length === 0) {
return doc.body.scrollTop || doc.documentElement.scrollTop
} else if (arg.length === 1) {
doc.body.scrollTop = arg[0]
doc.documentElement.scrollTop = arg[0]
return docTop()
}
}
return function () {
const tarTop = tar.offsetTop
const clickTop = docTop()
let status
if (clickTop < tarTop) status = 'down'
else status = 'up'
const SPEED = Math.abs(tarTop - clickTop) / 60
let lastTop = undefined
const scrollStep = function () {
let scrollTop = docTop()
lastTop = scrollTop
if (status === 'down') {
scrollTop += SPEED
if (scrollTop > tarTop) {
scrollTop = tarTop
status = 'stop'
}
} else if (status === 'up') {
scrollTop -= SPEED
if (scrollTop < tarTop) {
scrollTop = tarTop
status = 'stop'
}
}
const thisTop = docTop(scrollTop)
if (thisTop === lastTop) {
status = 'stop'
}
if (status === 'stop') {
return
}
requestAnimationFrame(scrollStep)
}
scrollStep()
}
} else {
return undefined
}
}