1.横向取值scrollLeft 竖向取值scrollTop
2.可以监听到最左最右侧
3.鼠标滚轮滑动控制滚动条滚动
效果
<template><div><div class="scrollable" ref="scrollableRef"><!-- 内容 --><div style="width: 2000px; height: 100px;">横向滚动内容</div></div><p>横向滚动位置: {{ scrollPosition }}</p><p v-if="isAtLeft">已滚动到最左侧</p><p v-if="isAtRight">已滚动到最右侧</p></div>
</template><script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';const scrollPosition = ref(0);
const isAtLeft = ref(false);
const isAtRight = ref(false);
const scrollableRef = ref(null);// 处理滚动事件
const handleScroll = () => {if (scrollableRef.value) {scrollPosition.value = scrollableRef.value.scrollLeft; // 获取横向滚动位置// 判断是否滚动到最左侧isAtLeft.value = scrollableRef.value.scrollLeft === 0;// 判断是否滚动到最右侧isAtRight.value = scrollableRef.value.scrollLeft + scrollableRef.value.clientWidth >= scrollableRef.value.scrollWidth;}
};// 处理鼠标滚轮事件
const handleWheel = (event) => {if (scrollableRef.value) {event.preventDefault(); // 防止默认的垂直滚动// 根据鼠标滚轮的方向调整 scrollLeftscrollableRef.value.scrollLeft += event.deltaY; // deltaY 表示垂直滚动的距离handleScroll(); // 更新滚动位置}
};// 添加和移除事件监听器
onMounted(() => {if (scrollableRef.value) {scrollableRef.value.addEventListener('scroll', handleScroll);scrollableRef.value.addEventListener('wheel', handleWheel); // 添加鼠标滚轮事件监听}
});onBeforeUnmount(() => {if (scrollableRef.value) {scrollableRef.value.removeEventListener('scroll', handleScroll);scrollableRef.value.removeEventListener('wheel', handleWheel); // 移除鼠标滚轮事件监听}
});
</script><style>
.scrollable {width: 300px; /* 设置宽度以启用横向滚动 */overflow-x: auto; /* 启用水平滚动 */border: 1px solid #ccc;
}
</style>