<template>
<div class="hello">
<div class="flash-list">
<div class="scroll-box">
<div
v-for="(item, index) in tabArr"
:key="index"
ref="pageContainer"
class="flash-item-info"
:class="active === index ? 'active' : ''"
@click="changeFlash(index, $event)"
>
<span class="desc">{{ item.title }}</span>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String,
},
data() {
return {
tabArr: [
{
title: "第1个",
},
{
title: "第2个",
},
{
title: "第3个",
},
{
title: "第4个",
},
{
title: "第5个",
},
{
title: "第6个",
},
{
title: "第7个",
},
{
title: "第8个",
},
{
title: "第9个",
},
{
title: "第10个",
},
],
currentIndex: 0,
active: 0,
};
},
methods: {
// 头部切换
changeFlash(index, event) {
this.active = index;
const spanLeft = event.clientX; //当前点击的元素左边距离
const totalWidths = document.body.clientWidth; //屏幕总宽度
const widths = totalWidths / 2; //一半的屏幕宽度
const spanRight = totalWidths - spanLeft; //元素的右边距离
const scrollBox = document.getElementsByClassName("flash-list"); //获取最外层的元素
const scrollL = scrollBox[0].scrollLeft; //滚动条滚动的距离
if (spanLeft > widths || spanRight > widths) {
//当元素左边距离大于屏幕一半宽度 或者 右边距离大于屏幕一半距离的时候
scrollBox[0].scrollLeft = scrollL + (spanLeft - widths); //滚动条最终的滚动距离
}
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.hello {
width: 100%;
}
.flash-list {
width: 100%;
height: 40px;
position: relative;
overflow-x: scroll;
overflow-y: hidden;
}
.scroll-box {
position: absolute;
height: 40px;
left: 0;
display: flex;
flex-flow: row nowrap;
}
.flash-item-info {
width: 50px;
height: 40px;
display: flex;
flex-flow: column nowrap;
justify-content: space-around;
align-items: center;
padding: 0 10px;
}
.active {
color: aqua;
}
</style>
tab菜单点击选中状态始终在屏幕可视区内
最新推荐文章于 2024-12-04 11:21:54 发布