效果图:可点击左右文字进行滚动、或通过滚动鼠标 内容左右滚动
<template>
<div class="Home">
<div style="display: flex;height: 100%;align-items: center;">
<div @click="scrollLeft()" style="width: 80px;text-align: center;font-size: 30px;">
左
</div>
<div ref="scrollContainerRef" class="testContent" @scroll="isSrcoll($event)">
<span v-for="item in 15" :key="item" class="test_card">
{{item}}
</span>
</div>
<div @click="scrollRight()" style="width: 80px;text-align: center;font-size: 30px;">
右
</div>
</div>
</div>
</template>
<script setup>
onMounted(() => {
let div = document.querySelector(".testContent");
// 监听 dom
div.addEventListener("wheel", function (e) {
let left = -e.wheelDelta || e.deltaY / 2;
// console.log("wheelDelta:", -e.wheelDelta, "deltaY :", e.deltaY);
// 修改滚动条位置
div.scrollLeft = div.scrollLeft + left;
});
});
//点击按钮横向滚动模块
let scrollContainerRef = ref(null)
const scrollLeft = () => {
scrollContainerRef.value.scrollBy({
left: -600, // 每次点击滚动的距离
behavior: 'smooth',
});
}
const scrollRight = () => {
scrollContainerRef.value.scrollBy({
left: 600, // 每次点击滚动的距离
behavior: 'smooth',
});
}
// 判断左右按钮是否显示(具体显示隐藏逻辑不写了)
const isSrcoll = (event) => {
let el = event.target;
if (Math.ceil(el.scrollLeft + el.clientWidth) >= el.scrollWidth) {
console.log("已滚动到最右侧");
}
if (!el.scrollLeft) {
console.log(el.scrollLeft, "左边左边");
}
}
</script>
<style scoped>
::-webkit-scrollbar {
/* 隐藏滚动条 */
display: none;
}
.testContent {
height: 100px;
width: 800px;
display: flex;
justify-content: space-between;
overflow-x: auto;
}
.test_card {
width: 220px;
height: 100%;
display: inline-block;
background: #a3a2a2;
margin-right: 5px;
flex-shrink: 0;
}
</style>