【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>
相关推荐
徐小夕6 分钟前
折腾一年,我们正式发布 JitOffice:一款跑在浏览器里的 AI Office
前端·vue.js·github
恋猫de小郭35 分钟前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter
zhanlang021736 分钟前
HTML 零基础入门到企业实战全套教程【第九章】企业开发规范与兼容适配|9.1 主流浏览器兼容问题与解决方案
前端·html
小码哥0681 小时前
短剧平台源码定制交付:批量导入剧集与媒体资源校验流程
前端·vue.js·媒体·短剧小程序·短剧系统·抖音短剧
晓得迷路了1 小时前
栗子前端技术周刊第 155 期 - 2026 HTML 现状调查报告、Solid 2.0...
前端·javascript·webpack
艾莉丝努力练剑1 小时前
【AI接入大模型SDK】Markdown格式解析
前端·c++·人工智能·学习·ai·架构
LinXunFeng2 小时前
A2UI 1.0 详解:让 AI 生成 Flutter 界面,还不怕它乱写
前端·flutter·agent
FRing0315 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng115 小时前
组件化服务端渲染模式SSR
前端
whitelbwwww16 小时前
CUDA C++实战--中级
开发语言·前端·c++