效果
核心代码
let spanLeft = event.clientX
let divBox = document.querySelector(".tabBoxs").clientWidth / 2
let totalWidths = document.body.clientWidth;
let widths = totalWidths / 2;
let spanRight = totalWidths - spanLeft;
let scrollBox = document.querySelector(".tabWraps");
let scrollL = scrollBox.scrollLeft;
if (spanRight < 400 || spanLeft < 400) {
scrollBox.scrollLeft = scrollL + (spanLeft - widths) + divBox;
}
封装成组件
<template>
<div class="tabWraps">
<div :class="['tabBox', crowdIndex == item.dictLabel && 'tabBoxs']" v-for="(item, index) in crowdList" :key="index"
@click="tabClick(item,$event)">
{{ item.dictLabel }}
</div>
</div>
</template>
<script setup>
const emit = defineEmits(['tabCkange'])
const props = defineProps(['crowdList'])
const data = reactive({
crowdIndex: '全部',
})
const { crowdIndex } = toRefs(data)
const tabClick = (item, event) => {
if (crowdIndex.value != item.dictLabel) {
crowdIndex.value = item.dictLabel
let spanLeft = event.clientX
let divBox = document.querySelector(".tabBoxs").clientWidth / 2
let totalWidths = document.body.clientWidth;
let widths = totalWidths / 2;
let spanRight = totalWidths - spanLeft;
let scrollBox = document.querySelector(".tabWraps");
let scrollL = scrollBox.scrollLeft;
if (spanRight < 400 || spanLeft < 400) {
scrollBox.scrollLeft = scrollL + (spanLeft - widths) + divBox;
}
emit('tabCkange', item.dictLabel)
}
}
</script>
<style lang="scss" >
.tabWraps{
width: 100%;
display: flex;
overflow-x: auto;
.tabBox {
flex-shrink: 0;
padding: 8px 24px;
font-size: 16px;
font-weight: 500;
color: #333333;
border-radius: 8px;
cursor: pointer;
}
.tabBoxs{
flex-shrink: 0;
padding: 8px 24px;
font-size: 16px;
font-weight: 500;
border-radius: 8px;
cursor: pointer;
background: #305AFF;
color: #FFFFFF;
}
}
.tabWraps::-webkit-scrollbar {
width: 0;
opacity: 0;
display: none;
}
</style>