【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>
相关推荐
正小安26 分钟前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch2 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光2 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   2 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   2 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web2 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
安冬的码畜日常2 小时前
【CSS in Depth 2 精译_044】第七章 响应式设计概述
前端·css·css3·html5·响应式设计·响应式
莹雨潇潇3 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
Jiaberrr3 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
Tiffany_Ho4 小时前
【TypeScript】知识点梳理(三)
前端·typescript