适用场景:类目切换,实现左滑右滑,上滑下滑,点击切换不同类目,被选中的类目移动到屏幕中间位置
watch: {
// 监听被选中的类目标签,使被选中的标签始终在屏幕中间显示
selectedIndex: {
handler: function() {
// 手机屏幕的宽度
let screenWidth = document.body.clientWidth;
// tabs元素
let waterfallTab = document.getElementById("waterfallTab");
console.log(screenWidth, "手机屏幕的宽度");
//使用setTimeout是因为不能实时的获取被点击的盒子,每次只能拿到上一次点击的盒子
setTimeout(() => {
// 被选中的tab元素
let active = document.getElementsByClassName("active")[0];
// 被选中的元素距离屏幕左侧的距离
let left = active.getBoundingClientRect().left;
console.log(left, "left");
//被选中盒子的宽度
let activeDivW = active.offsetWidth;
console.log(activeDivW, "被选中盒子的宽度");
// 应该居中的距离
let centerWidth = (screenWidth - activeDivW) / 2;
console.log(centerWidth, "应该居中的距离");
// 被选中盒子应该移动的距离
let moveWidth = left - centerWidth;
console.log(moveWidth, "被选中盒子应该移动的距离");
// tabs元素应该移动的距离
waterfallTab.scrollLeft += moveWidth;
});
},
},
},