/**
* scroller 滚动条元素
* to 滚动到位置
* duration 滚动时间
*/
function scrollLeftTo (scroller, to, duration) {
let rafId
let count = 0
const from = scroller.scrollLeft
const frames = duration === 0 ? 1 : Math.round((duration * 1000) / 16)
function cancel () {
cancelAnimationFrame(rafId)
}
function animate () {
scroller.scrollLeft += (to - from) / frames
if (++count < frames) {
rafId = requestAnimationFrame(animate)
}
}
animate()
return cancel
}
应用:
let activeTab = this.$el.querySelector('.is-active')
if (activeTab) {
let navScroll = this.$refs.navScroll
// 计算滚动位置
const to = activeTab.offsetLeft - (navScroll.offsetWidth - activeTab.offsetWidth) / 2
this.cancelScrollLeftToRaf && this.cancelScrollLeftToRaf()
this.cancelScrollLeftToRaf = scrollLeftTo(navScroll, to, 0.3)
}
效果: