HTML5 dragend event firing immediately

守給你的承諾、 提交于 2020-06-24 21:47:54

问题


I have several draggable elements

<div Class="question-item" draggable="true">Box 1: Milk was a bad choice.</div>
<div class="question-item" draggable="true">Box 2: I'm Ron Burgundy?</div>
<div class="question-item" draggable="true">Box 3: You ate the entire wheel of cheese?     </div>
<div class="question-item" draggable="true">Box 4: Scotch scotch scotch</div>

And I have the following event handlers:

var $questionItems = $('.question-item');

$questionItems
  .on('dragstart', startDrag)
  .on('dragend', removeDropSpaces)
  .on('dragenter', toggleDropStyles)
  .on('dragleave', toggleDropStyles);


function startDrag(e){
  console.log('dragging...');
  addDropSpaces();
  e.stopPropagation();
}

function toggleDropStyles(){
  $(this).toggleClass('drag-over');
  console.log(this);
}


function addDropSpaces(){
  $questionItems.after('<div class="empty-drop-target"></div>');
}

function removeDropSpaces(){
  console.log("dragend");
  $('.empty-drop-target').remove()
}

Why does it only work for the first draggable. If I drag say the last draggable - the dragend event is fired immediately. (I don't want to use jQuery UI btw)

It makes no sense to me - it looks like a bug.

I am on Chrome v 30 on OSX.

Here is a link to the JSFiddle: http://jsfiddle.net/joergd/zGSpP/17/

(Edit: this is repeat of the following question: dragend, dragenter, and dragleave firing off immediately when I drag - but I think the original poster was fine to go with jQuery UI, whereas I want it to be HTML5 native)


回答1:


As i mentioned in the topic dragend, dragenter, and dragleave firing off immediately when I drag , what solved the problem (which looks to be a Chrome bug) for me was to add a setTimeout of 10 milliseconds into the handler and manipulate the DOM in that timeout.




回答2:


I don't have a direct solution, but changing the DOM in the dragStart event handler is causing this problem, and any code that changes the DOM should really go in the dragEnter event handler - doing so, drag&drop events are fired more reliably.

Not sure whether this is by design - it feels a bit like a bug though.




回答3:


This is a known chrome issue. Problem is, as Joerg mentions that you manipulates the dom on dragstart.

You can do so, but you need to do it in a timeout.



来源:https://stackoverflow.com/questions/19639969/html5-dragend-event-firing-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!