如何修改现有拖拽Div代码以兼容Touch Events
触摸设备兼容的拖拽实现方案
直接修改现有代码即可同时兼容鼠标与触摸事件,核心是处理触摸事件的坐标获取逻辑及事件绑定,以下是完整修改后的代码:
JavaScript
dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; // 同时绑定鼠标和触摸开始事件 elmnt.onmousedown = dragStart; elmnt.ontouchstart = dragStart; function dragStart(e) { e = e || window.event; e.preventDefault(); // 区分鼠标/触摸事件,获取初始坐标 const touch = e.touches ? e.touches[0] : e; pos3 = touch.clientX; pos4 = touch.clientY; // 绑定移动与结束事件 document.onmousemove = elementDrag; document.ontouchmove = elementDrag; document.onmouseup = closeDragElement; document.ontouchend = closeDragElement; document.ontouchcancel = closeDragElement; // 处理触摸意外中断场景 } function elementDrag(e) { e = e || window.event; e.preventDefault(); // 区分鼠标/触摸事件,获取当前坐标 const touch = e.touches ? e.touches[0] : e; // 计算坐标变化量 pos1 = pos3 - touch.clientX; pos2 = pos4 - touch.clientY; pos3 = touch.clientX; pos4 = touch.clientY; // 边界限制逻辑保持不变 let parentElement = elmnt.parentElement; if (elmnt.offsetTop < 0) { elmnt.style.top = "0px"; return; } if (elmnt.offsetTop > (parentElement.offsetHeight - elmnt.offsetHeight) - 2) { elmnt.style.top = (parentElement.offsetHeight - elmnt.offsetHeight - 2) + "px"; return; } if (elmnt.offsetLeft < 0) { elmnt.style.left = "0px"; return; } if (elmnt.offsetLeft > (parentElement.offsetWidth - elmnt.offsetWidth) - 2) { elmnt.style.left = (parentElement.offsetWidth - elmnt.offsetWidth - 2) + "px"; return; } // 设置元素新位置 elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { // 移除所有事件绑定 document.onmousemove = null; document.ontouchmove = null; document.onmouseup = null; document.ontouchend = null; document.ontouchcancel = null; } }
CSS
#wrapper { height: 800px; width: 800px; border: 5px solid black; position: relative; } #mydiv { position: absolute; height: 60px; width: 60px; border: 5px solid black; background-color: red; /* 禁用浏览器默认触摸行为,避免干扰拖拽 */ touch-action: none; }
HTML
<div id="wrapper"> <div id="mydiv"> </div> </div>
核心修改点说明
- 事件绑定:同时为拖拽元素绑定
mousedown和touchstart事件,共用同一个启动逻辑 - 坐标适配:在事件处理函数中判断是否为触摸事件,通过
e.touches[0]获取触摸点的真实坐标 - 异常处理:新增
touchcancel事件绑定,处理触摸操作意外中断的情况 - 样式优化:给拖拽元素添加
touch-action: none,禁止浏览器默认的触摸滚动、缩放行为,避免拖拽被干扰
内容的提问来源于stack exchange,提问作者john young
相关产品推荐
相关产品推荐

