【Web系列二十七】Vue实现dom元素拖拽并限制移动范围

目录

需求

拖拽功能封装

使用拖拽功能

vite-env.d.ts

main.ts

test.vue


需求

dom元素拖拽并限制在父组件范围内

拖拽功能封装

javascript 复制代码
export const initVDrag = (vue) => {
	vue.directive('drag', (el) => {
		const oDiv = el // 当前元素
		oDiv.onmousedown = (e) => {
			let target = oDiv
			while (
				window.getComputedStyle(target).position !== 'absolute' &&
				target !== document.body
			) {
				target = target.parentElement
			}
			let parent = target.parentNode
			
			document.onselectstart = () => {
				return false
			}
			if (!target.getAttribute('init_x')) {
				target.setAttribute('init_x', target.offsetLeft)
				target.setAttribute('init_y', target.offsetTop)
			}
			
			// e.clientX, e.clientY是鼠标点击的位置
			// target.offsetLeft, target.offsetTop是当前元素左上角的位置
			// 计算鼠标按下的位置距离当前元素左上角的距离
			const disX = e.clientX - target.offsetLeft
			const disY = e.clientY - target.offsetTop
			// target.clientWidth, target.clientHeight是当前元素的尺寸
			// parent.clientWidth, parent.clientHeight是父元素的尺寸
			// parent.offsetLeft, parent.offsetTop是父元素左上角的位置
			// 可移动范围的位置
			const minX = parent.offsetLeft
			const maxX = parent.offsetLeft + parent.clientWidth - target.clientWidth
			const minY = parent.offsetTop
			const maxY = parent.offsetTop + parent.clientHeight - target.clientHeight
			
			document.onmousemove = (e) => {
				// 通过事件委托,计算移动的距离,e是最新的鼠标位置,disX、disY是鼠标刚点击时的位置
				let l = e.clientX - disX
				let t = e.clientY - disY
				
				// 约束移动范围在父元素区域内
				if (l < minX) {
					l = minX
				} else if (l > maxX) {
					l = maxX
				}
				if (t < minY) {
					t = minY
				} else if (t > maxY) {
					t = maxY
				}
				
				// 给当前元素样式中的left和top赋值
				target.style.left = l + 'px'
				target.style.top = t + 'px'
			}
			
			document.onmouseup = (e) => {
				document.onmousemove = null
				document.onmouseup = null
				document.onselectstart = null
			}
			
			// 不return false的话,可能导致鼠标黏连,鼠标粘在dom上拿不下来,相当于onmouseup失效
			return false
		}
	})
}

使用拖拽功能

以vite为例:

vite-env.d.ts

TypeScript 复制代码
...
declare module '@utils/directive/vDrag.js'
...

main.ts

TypeScript 复制代码
...
import { createApp } from 'vue'
import { initVDrag } from '@/utils/directive/vDrag.js'
...
let instance: any = null
instance = createApp(App)
initVDrag(instance)
...

test.vue

html 复制代码
<template>
    <div v-drag />
</template>
相关推荐
kyriewen1111 分钟前
WebAssembly:前端界的“外挂”,让C++代码在浏览器里跑起来
开发语言·前端·javascript·c++·单元测试·ecmascript
烛衔溟1 小时前
TypeScript 接口的基本使用 —— 定义对象形状
前端·javascript·typescript
铁皮饭盒2 小时前
成为AI全栈 - 第3课:路由 RESTful Elysia 状态码 设计规范
前端·后端·全栈
顾昂_2 小时前
Web 性能优化完全指南
前端·面试·性能优化
IT乐手2 小时前
Claude Code + Qwen 的配置方法
javascript·claude
前端程序媛-Tian2 小时前
前端 AI 提效实战:从 0 到 1 打造团队专属 AI 代码评审工具
前端·人工智能·ai
支付宝体验科技3 小时前
Ant Design Pro v6.0.0 发布
前端
T畅N3 小时前
审批流设计器(前端)
前端·elementui·vue·html·流程图·js
AlunYegeer3 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
IT_陈寒3 小时前
Redis这个内存杀手,差点让我们运维半夜追杀我
前端·人工智能·后端