You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改可拖拽文本域代码使其同时兼容PC端与移动端

问题原因

现有代码仅绑定了PC端的鼠标事件,移动端触摸操作触发的是独立的触摸事件体系,二者不兼容,因此移动端拖拽无响应。

适配代码

无需修改原有CSS和HTML结构,直接替换原有JavaScript代码即可同时兼容PC端与移动端:

// 初始化拖拽
dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  const dragHandle = document.getElementById(elmnt.id + "header") || elmnt;
  
  // 同时绑定鼠标和触摸启动事件
  dragHandle.onmousedown = dragStart;
  dragHandle.ontouchstart = dragStart;

  function dragStart(e) {
    e = e || window.event;
    e.preventDefault();
    // 统一获取坐标,兼容鼠标和触摸事件
    const point = e.touches ? e.touches[0] : e;
    pos3 = point.clientX;
    pos4 = point.clientY;
    // 绑定移动和结束事件
    document.onmouseup = dragClose;
    document.onmousemove = dragMove;
    document.ontouchend = dragClose;
    document.ontouchmove = dragMove;
  }

  function dragMove(e) {
    e = e || window.event;
    e.preventDefault();
    const point = e.touches ? e.touches[0] : e;
    // 计算新位置
    pos1 = pos3 - point.clientX;
    pos2 = pos4 - point.clientY;
    pos3 = point.clientX;
    pos4 = point.clientY;
    // 更新元素位置
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function dragClose() {
    // 清空所有事件绑定
    document.onmouseup = null;
    document.onmousemove = null;
    document.ontouchend = null;
    document.ontouchmove = null;
  }
}

可选优化

如果拖拽时出现移动端页面误触滚动的情况,可以给拖拽头部加CSS属性禁用默认触摸行为:

#mydivheader {
  touch-action: none;
}

内容的提问来源于stack exchange,提问作者Awais Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:48:02