<template>
<div
ref="scrollContainer"
class="scroll-container"
@mousedown="startScroll"
@mousemove="onScroll"
@mouseup="endScroll"
@mouseleave="endScroll">
<div class="scroll-content">
<ul>
<li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const isScrolling = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const items = [
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{id: 3, text: 'Item 3' },
{ id: 4, text: 'Item 4' },
{ id: 5, text: 'Item 5' },
{ id: 6, text: 'Item 6' },
{ id: 7, text: 'Item 7' },
{ id: 8, text: 'Item 8' },
{ id: 9, text: 'Item 9' },
{ id: 10, text: 'Item 10' },
// ...你的其他项目数据
]
const startScroll = (event) => {
isScrolling.value = true
startX.value = event.clientX
scrollLeft.value = scrollContainer.value.scrollLeft
}
const onScroll = (event) => {
if (!isScrolling.value) return
const deltaX = event.clientX - startX.value
scrollContainer.value.scrollLeft = scrollLeft.value - deltaX
}
const endScroll = () => {
isScrolling.value = false
}
const scrollContainer = ref(null)
return {
startScroll,
onScroll,
endScroll,
items,
scrollContainer
}
}
}
</script>
<style scoped>
.draggable, .scroll-container {
user-select: none;
}
.scroll-container {
margin-left: 20px;
overflow-x: auto;
width: 100px; /* 你可以根据需要调整这个值 */
position: relative;
cursor: grab;
}
.scroll-content {
display: inline-block;
white-space: nowrap;
}
.scroll-content ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.scroll-content ul li {
display: inline-block;
margin-right: 10px;
}
</style>
鼠标拖拽的一个demo (Vue3)
于 2024-10-30 15:08:11 首次发布