HTML5 dragend事件立即触发

时间:2013-10-28 16:21:05

标签: javascript html5 javascript-events drag-and-drop

我有几个可拖动的元素

<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>

我有以下事件处理程序:

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()
}

为什么它只适用于第一个可拖动的。如果我拖动说最后一个draggable - dragend事件立即被触发。 (我不想使用jQuery UI btw)

对我来说没有意义 - 它看起来像个错误。

我在OSX上的Chrome v 30上。

以下是JSFiddle的链接:http://jsfiddle.net/joergd/zGSpP/17/

(编辑:这是以下问题的重复:dragend, dragenter, and dragleave firing off immediately when I drag - 但我认为原始海报可以使用jQuery UI,而我希望它是HTML5原生的)

4 个答案:

答案 0 :(得分:11)

正如我在主题dragend, dragenter, and dragleave firing off immediately when I drag中提到的,为我解决问题(看起来像是一个Chrome错误)的原因是在处理程序中添加了10毫秒的setTimeout并在该超时时间内操作DOM。 / p>

答案 1 :(得分:6)

我没有直接的解决方案,但是在dragStart事件处理程序中更改DOM会导致此问题,并且任何更改DOM的代码都应该放在dragEnter事件处理程序中 - 这样做,拖放事件是发射得更可靠。

不确定这是否符合设计 - 但感觉有点像虫子。

答案 2 :(得分:3)

这是一个已知的铬问题。问题是,正如Joerg提到你在dragstart上操纵dom。

你可以这样做,但你需要在超时时间内完成。

答案 3 :(得分:0)

刚遇到同样的问题。我通过将元素位置更改为在 dragStart 中固定来操作 DOM。我使用 Ivan 的回答解决了我的问题,如下所示:

/* This function produced the issue */
function dragStart(ev) {
    /* some code */
    myElement.style.position="fixed";
}

/* This function corrected issue */
function dragStart(ev) {
    /*some code */
    setTimeout(function changePos() {
        myElement.style.position="fixed";
        }, 10);
}

看来您的问题的答案是

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