在移动设备上拖放使用一些代码来翻译事件(包括代码),但正常事件不起作用

Drag drop on mobile devices using some code that translates event (code included), but normal events are not working

本文关键字:代码 事件 包括 不起作用 常事件 翻译 移动 拖放      更新时间:2023-09-26

我使用下面的代码来允许在我的网站上触摸拖放。然而,虽然我的代码部分具有拖放功能,但在iPhone上,我无法滚动或移动页面。我可以拖动&但是普通的iPhone触摸功能已经消失了!

我在几个堆栈溢出响应中发现了下面的代码片段,所以我想知道是否有解决这个问题的方法。我希望能够拖动&在网页和手机上都可以点击。

我的拖拽代码(只是一个列表):

$(function() {
    $(".drag_me ul").sortable();
});

触摸事件代码:

function touchHandler(event)
{
 var touches = event.changedTouches,
    first = touches[0],
    type = "";
     switch(event.type)
{
    case "touchstart": type = "mousedown"; break;
    case "touchmove":  type="mousemove"; break;        
    case "touchend":   type="mouseup"; break;
    default: return;
}
var simulatedEvent = document.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
                          first.screenX, first.screenY,
                          first.clientX, first.clientY, false,
                          false, false, false, 0/*left*/, null);
first.target.dispatchEvent(simulatedEvent);
event.preventDefault();
}
function init()
{
   document.addEventListener("touchstart", touchHandler, true);
   document.addEventListener("touchmove", touchHandler, true);
   document.addEventListener("touchend", touchHandler, true);
   document.addEventListener("touchcancel", touchHandler, true);    
}

我一直在研究同样的问题,我想我刚刚成功了。我删除了touchHandler的核心,并使用它们来填充回调,该回调仅将事件侦听器绑定到<div id='stage'>的子节点。下面是我使用jquery的代码。希望这对你有帮助!

function init(){

 $("#stage").children().bind('touchstart touchmove touchend touchcancel', function(){
    var touches = event.changedTouches,    first = touches[0],    type = ""; 
    switch(event.type){    
      case "touchstart": type = "mousedown"; 
    break;    
      case "touchmove":  type="mousemove"; 
    break;            
      case "touchend":   type="mouseup"; 
    break;    
      default: return;
    }
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,
                      first.screenX, first.screenY,
                      first.clientX, first.clientY, false,
                      false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
  });
}

这行代码阻止了默认的滚动功能:

event.preventDefault();

由于此事件对象与文档绑定,因此所有本机卷轴都被禁用。

如果你想允许本地滚动页面,那么将事件侦听器添加到document元素的后代(这样,如果用户在可排序容器以外的区域滚动,他们将能够正常滚动页面)。

改变:

function init()
{
   document.addEventListener("touchstart", touchHandler, true);
   document.addEventListener("touchmove", touchHandler, true);
   document.addEventListener("touchend", touchHandler, true);
   document.addEventListener("touchcancel", touchHandler, true);    
}

:

function init()
{
   $('#sortable_container').bind('touchstart touchmove touchend touchcancel', touchHandler); 
}