效果圖:可點擊左右文字進行滾動、或通過滾動鼠標 內容左右滾動
<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");// 監聽 domdiv.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>