当我拖着时,dragend,dragenter和dragleave立即开火

Bil*_*ill 23 javascript jquery html5 drag-and-drop draggable

我正在尝试制作一个可以通过拖放重新定位的元素列表.第一个元素Box 1在100%的时间内都能正常工作.有时第二个框可以工作,但其他框都没有按预期工作.一旦你开始拖动它们,它们似乎立即触发所有拖动事件.

如果重要的话,我正在使用最新的Chrome(第23版).

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

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


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

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


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

function removeDropSpaces(){
  $('.empty-drop-target').remove();
  console.log('drop spaces removed');
}
Run Code Online (Sandbox Code Playgroud)

这是HTML:

<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>
Run Code Online (Sandbox Code Playgroud)

这是我的代码的jsFiddle:http://jsfiddle.net/zGSpP/5/

Iva*_*lev 29

刚刚遇到这个问题 - 这是一个Chrome bug,你不能在dragStart事件中操纵DOM,否则dragEnd会立即触发.我的解决方案原来是 - 使用setTimeout()并在你超时的函数内操作DOM.


sde*_*ont 8

它似乎是一个Chrome错误:https://groups.google.com/a/chromium.org/forum/?fromgroups =#! msg/chromium-bugs / YHs3orFC8Dc/rtT25b7J-NwJ

  • 这个错误仍然出现在 Chrome 32 中。 (2认同)
  • 在 Chrome 47 中似乎仍然遇到这个问题。 (2认同)
  • 仍然在Chrome 62中:/ (2认同)

Joe*_*erg 6

不确定它是否是一个bug,但我认为当你在dragstart处理程序中更改DOM时会出现问题.我认为第一个盒子工作的原因与它的位置在DOM中的其他盒子之前的事实有关,当你改变DOM时,第一个盒子的位置(?)不受影响,并且拖拉事件火力可靠.

您需要稍微重构一下代码,并在dragenter事件处理程序中添加dropSpaces.您需要更改addDropSpaces方法以适应它将被多次调用的事实.


小智 -1

改变这个功能

function addDropSpaces()
{
  $(this).after('<div class="empty-drop-target"></div>');
}
Run Code Online (Sandbox Code Playgroud)

在您的版本中,您将在每个 $questionItems 之后添加该 div。