PC端横向滚动—Vue3.md
<template>
<div class="scroll-container" @mousedown="startDrag" @mousemove="onDrag" @mouseup="stopDrag" @mouseleave="stopDrag">
<div class="scroll-content" ref="scrollContent">
<1--不一定要这样,放入需要滚动的列表即可,外部一定要套两层,第一层是确定他的框架,超过了就隐藏,第二层则是设置他的滚动以及他的滚动距离-->
<div class="scroll-item" v-for="item in items" :key="item.id">{{ item.name }}</div>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
const scrollContent = ref(null);
const items = ref([
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' },
{ id: 4, name: 'Item 4' },
{ id: 5, name: 'Item 5' },
{ id: 6, name: 'Item 6' }
]);
let isDragging = false;
let startX = 0;
let scrollLeft = 0;
// isDragging 当用户鼠标按下,isDragging设置为真,为后面鼠标移动事件做铺垫
const startDrag = (e) => {
isDragging = true;
startX = e.pageX - scrollContent.value.offsetLeft;
scrollLeft = scrollContent.value.scrollLeft; //可见内容与实际内容距离
};
const onDrag = (e) => {
if (!isDragging) return;
e.preventDefault();
const x = e.pageX - scrollContent.value.offsetLeft;
const walk = (x - startX) * 2; // 滚动速度
scrollContent.value.scrollLeft = scrollLeft - walk;
};
// 鼠标事件抬起 isDragging设为false,让鼠标移动事件失效
const stopDrag = () => {
isDragging = false;
};
</script>
<style scoped>
.scroll-container {
display: flex;
align-items: center;
overflow: hidden;
user-select: none; /* 防止拖动时选择文本 */
}
.scroll-content {
display: flex;
overflow-x: auto;
scroll-behavior: smooth;
/* scroll-behavior属性包括: smooth | auto; */
/* auto: 默认值,表示滚动框立即滚动到指定位置。 smooth 表示允许滚动时采用平滑过渡,而不知直接滚动到相应位置,最常见的比如回到顶部按钮和锚点。 */
cursor: grab;
width: 100%; /* 根据需要调整宽度*/
}
.scroll-content:active {
cursor: grabbing; // 爪子
}
.scroll-item {
min-width: 100px;
margin: 0 10px;
padding: 10px;
background-color: #f0f0f0;
border: 1px solid #ccc;
text-align: center;
white-space: nowrap;
}
/* 隐藏滚动条 这样用户体验更好 */
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}
</style>