效果 :点击左右两个按钮达到切换效果(利用transform 进行平移)
<div class="app">
<div class="tab-wrap">
<div class="tab">
<div ref="itemWrap" class="item-wrap" :style="{transform: `translateX(${distance}px)`}">
<div v-for="(item,index) in 20" :key="index" class="item" :class="{active:index===tabActive}" @click="tabActive = index">
tab {{item}}
</div>
</div>
</div>
<div class="btn left" @click="arrow(1)">left</div>
<div class="btn right" @click="arrow(-1)">right</div>
</div>
</div>
<script src="../vue.js"></script>
<script src="./index.js"></script>
new Vue({
el: '.app',
data() {
return {
message: 'aaaaaaaaaaa',
tabActive: 0, // 激活样式
distance: 0, // tab 滚动(移动)的距离
}
},
created() {},
mounted() {},
methods: {
// 移动tab
arrow(num) {
const dom = this.$refs.itemWrap
const domWidth = dom.clientWidth // 拿到当前盒子宽度
const parentDomWidth = dom.parentNode.clientWidth // 拿到展示宽度(及父级宽度)
if (domWidth < parentDomWidth) return
this.distance += parentDomWidth * num * 0.6
if (this.distance > 0) {
this.distance = 0
}
const maxDistance = -(domWidth - parentDomWidth) // 可移动最大宽度
if (this.distance < maxDistance) {
this.distance = maxDistance
}
},
},
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
overflow: hidden;
}
.app{
/* color: red; */
font-size: 16px;
/* display: flex;
align-items: center;
justify-content: center; */
}
.tab-wrap{
width: 100vw;
height: 80px;
padding:0 60px;
position: relative;
background: #f1f6fe;
}
.tab {
overflow: hidden;
padding-top: 20px;
height: 100%;
position: relative;
}
.item-wrap {
display: flex;
height: 100%;
transition: transform 0.3s;
width: max-content;
position: absolute;
/* width: max-content; 将盒子宽度取所有子集的宽度之和 且不缩放*/
}
.item {
padding: 10px 20px;
background: #f5f5f5;
margin-right: 10px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
background: rgba(110, 158, 248, 0.1);
}
.item.active{
background: rgba(110, 158, 248, 1);
color: #fff;
}
.btn {
position: absolute;
top: 0;
width: 50px;
height: 100%;
background: rgba(110, 158, 248, 0.4);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.left{
left: 0;
}
.right{
right: 0;
}