演示效果:就几行代码懒得录屏,自己复制到vue项目看就行了
<template>
<div class="menu">
<div
class="menu-item"
v-for="(item, index) in tabList"
:key="index"
@click="toggleTab(index)"
>
{{ item }}
</div>
<div class="link" :style="{ left: left + 'px' }"></div>
</div>
</template>
<script>
export default {
data() {
return {
tabList: ["自选服自选服777", "市值", "大盘", "排行"],
left: null,
tabIndex: 0,
}
},
mounted() {
this.getLeftPx(0)
},
methods: {
toggleTab(index) {
this.getLeftPx(index)
this.tabIndex = index
},
getLeftPx(index) {
let linkWitch = document.querySelector(".link").clientWidth
let menuItem = document.querySelectorAll(".menu-item")
let menuItemWitch = menuItem[index].clientWidth
this.left =
menuItemWitch * index + menuItemWitch / 2 - linkWitch / 2
},
},
}
</script>
<style scoped>
.menu {
width: 400px;
margin: 0 auto;
display: flex;
position: relative;
}
.menu-item {
flex: 1;
cursor: pointer;
}
.link {
width: 20px;
height: 4px;
background: red;
border-radius: 20px;
position: absolute;
bottom: 0;
transition: all 0.3s;
}
</style>