本文共 2452 字,大约阅读时间需要 8 分钟。
拖拽功能在前端开发中是一个常见的需求,常见的实现方式有两个:基于h5拖拽属性的实现和基于鼠标事件的模拟实现。两种方式各有优缺点,可以根据实际需求选择合适的方式。
1、基于h5拖拽属性的实现
函数myDrag(el){ 变量disX,disY,left,top; el.draggable = true; el.ondragstart = 函数(e){ disX = e.clientX; disY = e.clientY; left = parseInt(window.getComputedStyle(el).marginLeft); top = parseInt(window.getComputedStyle(el).marginTop); } el.ondrag = 函数(e){ 如果(e.clientX>0 || e.clientY>0){ l = e.clientX - disX; t = e.clientY - disY; el.style.marginLeft = left + l + 'px'; el.style.marginTop = top + t + 'px'; } } el.ondragend = 函数(e){ }
2、基于鼠标事件的模拟拖拽
函数myDrag(el){ el.draggable = false; el.onmousedown = 函数(e){ disX = e.clientX; disY = e.clientY; left = parseInt(window.getComputedStyle(el).marginLeft); top = parseInt(window.getComputedStyle(el).marginTop); document.onmousemove = 函数(e){ l = e.clientX - disX; t = e.clientY - disY; el.style.marginLeft = left + l + 'px'; el.style.marginTop = top + t + 'px'; }; document.onmouseup = 函数(e){ document.onmousemove = null; document.onmouseup = null; }; }
在前端框架Vue中,可以通过自定义指令来实现拖拽功能,常见的场景是实现面板的拖拽。例如,在一个面板中,标题部分可以被配置为可拖拽的元素,拖拽时面板会随标题移动。以下是实现步骤:
Vue.directive('drag', { bind: 函数(el, binding, vnode){ el.draggable = false; el.onmousedown = 函数(e){ el.parentNode.draggable = false; disX = e.clientX; disY = e.clientY; left = parseInt(window.getComputedStyle(el.parentNode).marginLeft); top = parseInt(window.getComputedStyle(el.parentNode).marginTop); document.onmousemove = 函数(e){ l = e.clientX - disX; t = e.clientY - disY; el.parentNode.style.marginLeft = left + l + 'px'; el.parentNode.style.marginTop = top + t + 'px'; }; document.onmouseup = 函数(e){ document.onmousemove = null; document.onmouseup = null; }; }
...
这一实现方式需确保该面板可以自由地在页面中移动,并且可以通过回调接口(如binding.value(l,t))获取拖拽时的坐标位移信息。需要注意的是,拖拽过程中需要确保事件处理函数能够及时释放,以避免内存泄漏或页面响应速度的下降。
转载地址:http://yqxdz.baihongyu.com/