当前位置:首页 > VUE

Vue实现鼠标拖拽滚动

2026-02-22 11:20:27VUE

实现鼠标拖拽滚动的基本思路

在Vue中实现鼠标拖拽滚动效果,核心是监听鼠标事件(mousedown、mousemove、mouseup)并计算位移差。通过修改元素的scrollLeft或scrollTop属性实现滚动效果。

基础实现步骤

创建可拖拽滚动的容器组件,模板部分需设置overflow: hidden样式:

<template>
  <div 
    class="scroll-container"
    ref="container"
    @mousedown="startDrag"
    @mousemove="onDrag"
    @mouseup="endDrag"
    @mouseleave="endDrag"
  >
    <slot></slot>
  </div>
</template>

脚本部分处理拖拽逻辑:

Vue实现鼠标拖拽滚动

export default {
  data() {
    return {
      isDragging: false,
      startX: 0,
      scrollLeft: 0
    }
  },
  methods: {
    startDrag(e) {
      this.isDragging = true
      this.startX = e.pageX - this.$refs.container.offsetLeft
      this.scrollLeft = this.$refs.container.scrollLeft
    },
    onDrag(e) {
      if (!this.isDragging) return
      e.preventDefault()
      const x = e.pageX - this.$refs.container.offsetLeft
      const walk = (x - this.startX) * 2 // 调整系数控制滚动速度
      this.$refs.container.scrollLeft = this.scrollLeft - walk
    },
    endDrag() {
      this.isDragging = false
    }
  }
}

样式优化

为提升用户体验,建议添加拖拽时的光标样式:

.scroll-container {
  overflow-x: auto;
  cursor: grab;
  user-select: none;
}

.scroll-container:active {
  cursor: grabbing;
}

垂直滚动支持

若需支持垂直方向拖拽,修改方法如下:

Vue实现鼠标拖拽滚动

startDrag(e) {
  this.isDragging = true
  this.startY = e.pageY - this.$refs.container.offsetTop
  this.scrollTop = this.$refs.container.scrollTop
},
onDrag(e) {
  if (!this.isDragging) return
  const y = e.pageY - this.$refs.container.offsetTop
  const walk = y - this.startY
  this.$refs.container.scrollTop = this.scrollTop - walk
}

性能优化建议

对于复杂内容,可使用防抖技术减少重绘:

import { debounce } from 'lodash'

methods: {
  onDrag: debounce(function(e) {
    // 拖拽逻辑
  }, 16) // 60fps的帧间隔
}

移动端兼容

添加触摸事件支持以实现移动端适配:

<div
  @touchstart="startDrag"
  @touchmove="onDrag"
  @touchend="endDrag"
></div>

触摸事件处理方法需调整坐标获取方式:

startDrag(e) {
  const clientX = e.touches ? e.touches[0].clientX : e.clientX
  // 其余逻辑相同
}

标签: 鼠标拖拽
分享给朋友:

相关文章

vue实现列拖拽

vue实现列拖拽

Vue 实现列拖拽功能 使用原生 HTML5 拖放 API 在 Vue 中可以通过原生 HTML5 的拖放 API 实现列拖拽功能。需要处理 draggable、dragstart、dragover…

vue如何实现拖拽

vue如何实现拖拽

实现拖拽的基本方法 在Vue中实现拖拽功能通常使用HTML5的Drag and Drop API或第三方库如vuedraggable。以下是两种方法的详细说明。 使用HTML5 Drag and D…

vue实现拖拽互换

vue实现拖拽互换

Vue 实现拖拽互换 在 Vue 中实现拖拽互换功能可以通过原生 HTML5 的拖放 API 或第三方库如 vuedraggable 来完成。以下是两种方法的实现方式: 使用 HTML5 拖放 AP…

vue 实现拖拽替换

vue 实现拖拽替换

Vue 实现拖拽替换 在 Vue 中实现拖拽替换功能可以通过 HTML5 的拖放 API 结合 Vue 的事件绑定和数据响应式特性来完成。以下是实现拖拽替换的详细方法: 设置拖拽元素 为需要拖拽的元…

vue实现按钮拖拽

vue实现按钮拖拽

Vue 实现按钮拖拽功能 使用 HTML5 拖放 API 在 Vue 中实现按钮拖拽功能,可以借助 HTML5 的拖放 API。以下是一个简单的实现示例: <template> &l…

vue实现固定块拖拽

vue实现固定块拖拽

Vue 实现固定块拖拽 使用 HTML5 原生拖拽 API 在 Vue 中可以通过 HTML5 的拖拽 API 实现固定块的拖拽功能。需要监听 dragover、dragstart 和 drop 事件…