HTML5 DragDrop Enter 和 Leave 事件依次被调用

HTML5 DragDrop Enter and Leave event is called one after another

我有一个非常简单的拖放效果,方法是在拖动进入(或结束)和离开时更改 class 名称。然而,我正在经历不断的进进出出。

看看这个简单的 HTML 代码

<div class="box">
  <div class="childbox"></div>
</div>

这是我的CSS

.box {
  position: relative;
  width: 80%;
  height: 300px;
  border: 1px solid black;
}

.box.dragover:after {
  position: absolute;
  background-color: rgba(0, 255, 0, 0.05);
  content: '';
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.childbox {
  position: relative;
  width: 100%;
  height: 100%;
}

这是我的脚本

$('.box').on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
  e.preventDefault();
  e.stopPropagation();
}).bind('dragover dragenter', function(e) {
  e.stopPropagation();
  $(this).addClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + ' --- Target: ' + this.className);
}).bind('dragleave dragend drop', function(e) {
  e.stopPropagation();
  $(this).removeClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + ' --- Target: ' + this.className);
});

我已经创建了 jsfiddle https://jsfiddle.net/n71udevm/1/,如果您尝试将任何文件拖到框中,它会创建从绿色到白色的闪烁效果。这是因为dragenterdragleave事件是相继调用的。

我怀疑它是由 box.dragover:after 引起的。知道如何解决吗?

谢谢...

pointer-events: none 添加到 :after。这将使 :after 不响应鼠标事件,包括您在代码中提到的所有事件。

.box.dragover:after {
  pointer-events: none; /* <- here */
}

$('.box').on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  e.preventDefault();
  e.stopPropagation();
}).bind('dragover dragenter', function (e) {
  e.stopPropagation();
  $(this).addClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + '   ---   Target: ' + this.className);
}).bind('dragleave dragend drop', function (e) {
  e.stopPropagation();
  $(this).removeClass('dragover');
  console.log('\nEvent: ' + e.originalEvent.type + '   ---   Target: ' + this.className);
})
.box {
  position: relative;
  width: 80%;
  height: 300px;
  border: 1px solid black;
}

.box.dragover:after {
  pointer-events: none;
  position: absolute;
  background-color: rgba(0, 255, 0, 0.05);
  content: '';
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.childbox {
  position: relative;
  width: 100%;
  height: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
  <div class="childbox">
  
  </div>
</div>

https://jsfiddle.net/moshfeu/24bvshan/