[javascript] 터치 장치 용 자바 스크립트 드래그 앤 드롭 [닫기]

터치 장치에서 작동하는 드래그 앤 드롭 플러그인을 찾고 있습니다.

“droppable”요소를 허용 하는 jQuery UI 플러그인 과 유사한 기능을 원합니다 .

플러그인 jqtouch 드래그 지원,하지만 낙하.

여기에 드래그 &에만 아이폰 / 아이 패드를 지원하는 드롭입니다.

누구든지 Android / ios에서 작동하는 드래그 앤 드롭 플러그인의 방향을 알려줄 수 있나요?

… 또는 드롭 가능성을 위해 jqtouch 플러그인을 업데이트 할 수 있습니다. 이미 Andriod 및 IOS에서 실행됩니다.

감사!



답변

마우스 이벤트를 필요한 터치로 변환하는 추가 라이브러리와 함께 드래그 앤 드롭에 Jquery UI를 사용할 수 있습니다. 제가 권장하는 라이브러리는 https://github.com/furf/jquery-ui-touch-punch 입니다. 이것은 Jquery UI에서 드래그 앤 드롭이 터치 장치에서 작동합니다.

또는 내가 사용중인이 코드를 사용할 수 있으며 마우스 이벤트를 터치로 변환하고 마법처럼 작동합니다.

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.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);
}

그리고 document.ready에서 init () 함수를 호출하십시오.

여기 에서 찾은 코드


답변

이것을 사용하고 ‘클릭’기능을 유지하려는 사람은 (John Landheer가 그의 의견에서 언급했듯이) 몇 가지 수정 만하면됩니다.

몇 가지 전역을 추가합니다.

var clickms = 100;
var lastTouchDown = -1;

그런 다음 원래의 switch 문을 다음과 같이 수정합니다.

var d = new Date();
switch(event.type)
{
    case "touchstart": type = "mousedown"; lastTouchDown = d.getTime(); break;
    case "touchmove": type="mousemove"; lastTouchDown = -1; break;
    case "touchend": if(lastTouchDown > -1 && (d.getTime() - lastTouchDown) < clickms){lastTouchDown = -1; type="click"; break;} type="mouseup"; break;
    default: return;
}

취향에 따라 ‘클릭 수’를 조정할 수 있습니다. 기본적으로 클릭을 시뮬레이션하기 위해 ‘터치 스타트’와 ‘터치 엔드’를 빠르게 지켜 보는 것입니다.


답변

위의 코드에 감사드립니다! -몇 가지 옵션을 시도했는데 이것이 티켓이었습니다. 나는 preventDefault가 ipad에서 스크롤을 막고 있다는 문제가 있었다. 나는 지금 드래그 가능한 항목을 테스트하고 있으며 지금까지 훌륭하게 작동한다.

if (event.target.id == 'draggable_item' ) {
    event.preventDefault();
}


답변

gregpress answer 와 동일한 솔루션이 있었지만 드래그 가능한 항목은 ID 대신 클래스를 사용했습니다. 작동하는 것 같습니다.

var $target = $(event.target);
if( $target.hasClass('draggable') ) {
    event.preventDefault();
}


답변

내가 아는 오래된 실 …….

@ryuutatsuo의 답변에 대한 문제는 ‘클릭'(예 : 입력)에 반응해야하는 입력 또는 기타 요소도 차단한다는 것이므로이 솔루션을 작성했습니다. 이 솔루션을 통해 모든 터치 장치 (또는 컴퓨터)에서 mousedown, mousemove 및 mouseup 이벤트를 기반으로하는 기존의 드래그 앤 드롭 라이브러리를 사용할 수 있습니다. 이것은 또한 브라우저 간 솔루션입니다.

여러 장치에서 테스트 한 결과 빠르게 작동합니다 (ThreeDubMedia의 드래그 앤 드롭 기능과 함께 사용됩니다 ( http://threedubmedia.com/code/event/drag 참조).). jQuery 솔루션이므로 jQuery libs에서만 사용할 수 있습니다. 내가 사용하고 jQuery를 1.5.1을 몇 가지 있기 때문에 그것을 위해 새로운 기능을 위 IE9에서 제대로 작동하지 않습니다 (jQuery를 최신 버전으로 테스트하지).

이벤트에 끌어서 놓기 작업을 추가 하기 전에 먼저이 함수를 호출해야합니다 .

simulateTouchEvents(<object>);

또한 다음 구문을 사용하여 입력을 위해 모든 구성 요소 / 하위 항목을 차단하거나 이벤트 처리 속도를 높일 수 있습니다.

simulateTouchEvents(<object>, true); // ignore events on childs

내가 작성한 코드는 다음과 같습니다. 평가 속도를 높이기 위해 멋진 트릭을 사용했습니다 (코드 참조).

function simulateTouchEvents(oo,bIgnoreChilds)
{
 if( !$(oo)[0] )
  { return false; }

 if( !window.__touchTypes )
 {
   window.__touchTypes  = {touchstart:'mousedown',touchmove:'mousemove',touchend:'mouseup'};
   window.__touchInputs = {INPUT:1,TEXTAREA:1,SELECT:1,OPTION:1,'input':1,'textarea':1,'select':1,'option':1};
 }

$(oo).bind('touchstart touchmove touchend', function(ev)
{
    var bSame = (ev.target == this);
    if( bIgnoreChilds && !bSame )
     { return; }

    var b = (!bSame && ev.target.__ajqmeclk), // Get if object is already tested or input type
        e = ev.originalEvent;
    if( b === true || !e.touches || e.touches.length > 1 || !window.__touchTypes[e.type]  )
     { return; } //allow multi-touch gestures to work

    var oEv = ( !bSame && typeof b != 'boolean')?$(ev.target).data('events'):false,
        b = (!bSame)?(ev.target.__ajqmeclk = oEv?(oEv['click'] || oEv['mousedown'] || oEv['mouseup'] || oEv['mousemove']):false ):false;

    if( b || window.__touchInputs[ev.target.tagName] )
     { return; } //allow default clicks to work (and on inputs)

    // https://developer.mozilla.org/en/DOM/event.initMouseEvent for API
    var touch = e.changedTouches[0], newEvent = document.createEvent("MouseEvent");
    newEvent.initMouseEvent(window.__touchTypes[e.type], true, true, window, 1,
            touch.screenX, touch.screenY,
            touch.clientX, touch.clientY, false,
            false, false, false, 0, null);

    touch.target.dispatchEvent(newEvent);
    e.preventDefault();
    ev.stopImmediatePropagation();
    ev.stopPropagation();
    ev.preventDefault();
});
 return true;
}; 

기능 : 처음에는 단일 터치 이벤트를 마우스 이벤트로 변환합니다. 드래그해야하는 요소 위 / 안의 요소로 인해 이벤트가 발생했는지 확인합니다. input, textarea 등과 같은 입력 요소 인 경우 번역을 건너 뛰거나 표준 마우스 이벤트가 첨부 된 경우 번역도 건너 뜁니다.

결과 : 드래그 가능한 요소의 모든 요소가 계속 작동합니다.

즐거운 코딩, greetz, Erwin Haantjes


답변