Vue實現(xiàn)dom元素拖拽并限制移動范圍的操作代碼
更新時間:2023年12月04日 16:44:56 作者:Nicholson07
這篇文章主要介紹了Vue實現(xiàn)dom元素拖拽并限制移動范圍的操作代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
需求
dom元素拖拽并限制在父組件范圍內(nèi)
拖拽功能封裝
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 // 約束移動范圍在父元素區(qū)域內(nèi) 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
... declare module '@utils/directive/vDrag.js' ...
main.ts
... import { createApp } from 'vue' import { initVDrag } from '@/utils/directive/vDrag.js' ... let instance: any = null instance = createApp(App) initVDrag(instance) ...
test.vue
<template> <div v-drag /> </template>
到此這篇關于Vue實現(xiàn)dom元素拖拽并限制移動范圍的文章就介紹到這了,更多相關vue dom元素拖拽內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue2安裝使用MonacoEditor方式(自定義語法,自定義高亮,自定義提示)
這篇文章主要介紹了Vue2安裝使用MonacoEditor方式(自定義語法,自定義高亮,自定義提示),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04Vue3中的?computed,watch,watchEffect的使用方法
這篇文章主要介紹了Vue3中的?computed,watch,watchEffect的使用方法,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價價值,需要得小伙伴可以參考一下2022-06-06Vue3中的ref為何要用.value進行值的調(diào)用呢
這篇文章主要介紹了Vue3中的ref為何要用.value進行值的調(diào)用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09公共Hooks封裝useTableData表格數(shù)據(jù)實例
這篇文章主要為大家介紹了公共Hooks封裝useTableData表格數(shù)據(jù)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12