vue中操作dom,实现元素的拖拉拽
使用原生的操作DOM的方式,实现元素的拖拉拽功能。默认将元素绝对定位到左上角位置left为0,top为0。监听元素的移动,只需要知道元素的左上角x和y位置即可,元素的x和y的偏移量就是元素重新进行定位的left和top的数据。
getBoundingClientRect() 是 DOM 元素的一个方法,它返回一个 DOMRect 对象,提供了元素的大小及其相对于视口(viewport)的位置信息。
具体代码:
<template><divref="draggable"class="draggable-box"@mousedown="startDrag">拖拽我 (自定义实现)</div>
</template><script setup>
import { ref, onMounted, onUnmounted } from 'vue'const draggable = ref(null)
let isDragging = false; // 是否拖动
let offsetX = 0
let offsetY = 0const startDrag = (e) => {isDragging = true// 计算鼠标相对于元素左上角的偏移// getBoundingClientRect() 是 DOM 元素的一个方法,它返回一个 DOMRect 对象,提供了元素的大小及其相对于视口(viewport)的位置信息。const rect = draggable.value.getBoundingClientRect();// console.log(`元素距离视口左侧: ${rect.left}px`);// console.log(`元素距离视口顶部: ${rect.top}px`);offsetX = e.clientX - rect.left; offsetY = e.clientY - rect.top// 添加样式draggable.value.style.cursor = 'grabbing'draggable.value.style.userSelect = 'none'// 阻止默认行为防止文本选中e.preventDefault()
}const onMouseMove = (e) => {if (!isDragging) return// 计算新位置const x = e.clientX - offsetXconst y = e.clientY - offsetY// 应用新位置draggable.value.style.left = `${x}px`draggable.value.style.top = `${y}px`
}const stopDrag = () => {isDragging = falseif (draggable.value) {draggable.value.style.cursor = 'grab'draggable.value.style.userSelect = ''}
}onMounted(() => {// 初始位置draggable.value.style.position = 'absolute'draggable.value.style.left = '0px'draggable.value.style.top = '0px'// 添加事件监听document.addEventListener('mousemove', onMouseMove)document.addEventListener('mouseup', stopDrag)
})onUnmounted(() => {// 移除事件监听document.removeEventListener('mousemove', onMouseMove)document.removeEventListener('mouseup', stopDrag)
})
</script><style>
.draggable-box {width: 100px;height: 100px;background-color: #e74c3c;color: white;display: flex;justify-content: center;align-items: center;cursor: grab;user-select: none;
}
</style>