本篇文章分别实现的两个需求:1、滚动条显示自定义;2、无滚动条时 鼠标滑轮水平滑动;
HTML:
<div class="tab-container">
<div class="tab-container-main">
<div
class="tab-container-main-item"
:class="[{ active: activeKey == item.key }, { back: isback && activeKey == item.key }]"
:key="`tab_${item.index}`"
:tab="item.title"
v-for="item in TabList"
@click="handleItem(item)"
>
{{ item.title }}
</div>
</div>
</div>
//假设会有很多的对象
const TabList = [
{
title: '系统预设模版',
key: '1'
},
{
title: '企业发布模版',
key: '2'
},
{
title: '模版草稿箱',
key: '3'
}
];
CSS:
.tab-container {
background: #fff;
&-main {
display: flex;
position: relative;
overflow: auto; //必须设置这个才能让元素水平滑动
white-space: nowrap; //不换行
transform: translate(0);
transition: transform 0.3s;
// scrollbar-width: none; //也可以不显示滚动条
// scrollbar-color: red #0ff; //滚动条颜色设置
&-item {
padding: 10px 20px;
cursor: pointer;
font-weight: bold;
color: #88909b;
font-size: 20px;
transition: 0.3s all;
&:hover {
// background: #f5f5f5;
transition: 0.3s all;
color: #0e56c0;
}
}
.active {
// background: #f5f5f5;
color: #0e56c0;
position: relative;
&::after {
content: '';
position: absolute;
background: #f5f5f5;
background: #0e56c0;
width: 20%;
height: 3px;
border-radius: 15px;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
}
.back {
background: #e7eef9;
color: #0e56c0;
border-radius: 10px 10px 0 0;
}
}
}
onMounted
const scrollableBox = document.querySelector('.tab-container-main');
//要保证这个.tab-container-main是唯一类名,才能实现滚动,要不就用getElementById
// 添加鼠标滚轮事件监听
scrollableBox.addEventListener('wheel', (event) => {
event.preventDefault(); // 阻止默认滚动行为
const delta = Math.sign(event.deltaY); // 获取滚轮滚动方向
scrollableBox.scrollLeft += delta * 30; // 根据方向调整滚动位置
},{ passive: false });
//passive: false选项在addEventListener中用于阻止浏览器的默认滚动行为,也可以不加,我的项目中就没有加这个设置