模拟vant的Tab标签页的标签滚动效果
效果:选中元素,在滚动条的可视区域里面自动居中,头尾两端不用居中
vant效果:https://youzan.github.io/vant/#/zh-CN/tab
start() {
/**
* 1)先让选中的元素滚到可视区域的最左边 scrollLeft
* 2)接着向右移动容器一半的距离 containWidth / 2
* 3)最后向左移动item一半的距离 offsetWidth / 2
*/
let lastSpot = this.$refs.scrollBox.scrollLeft;
const nextSpace = 7; //每次移动距离
let scrollItemTimer = setInterval(() => {
this.$nextTick(() => {
let offsetWidth = this.$refs.scrollItem[this.currentIndex].offsetWidth; //item
let scrollLeft = this.$refs.scrollItem[this.currentIndex].offsetLeft; //选中的元素滚到可视区域的最左边
const containWidth = this.$refs.scrollBox.offsetWidth; //容器的宽度
let resultSpot = scrollLeft + offsetWidth / 2 - containWidth / 2; //最终要停留的点
if (Math.abs(lastSpot - resultSpot) < nextSpace) {
clearInterval(scrollItemTimer);
}
if (resultSpot >= lastSpot) {
lastSpot = lastSpot + nextSpace;
} else {
lastSpot = lastSpot - nextSpace;
}
this.$refs.scrollBox.scrollTo(lastSpot, 0);
});
}, 15);
},