鼠标拖拽的一个demo (Vue3)

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值