如何在拖动事件监听器中获取放置效果值?

时间:2016-09-24 05:34:17

标签: javascript html html5 drag-and-drop

有一个可拖动的元素和droppable元素。 Droppable元素在event.dataTransfer.dropEffect事件上将值设置为dragover属性。根据设计,拖动元素的dropEffect事件侦听器中的drag值应该具有dragover事件侦听器设置的保存值。问题是dropEffect事件监听器中none值始终为drag

是否可以在拖动元素的dropEffect事件侦听器中获取dragover值(由drag事件侦听器设置)?

以下是一个示例(拖动可放置元素时,可拖动元素文本应更改为copymove):



var draggable = document.getElementById( 'draggable' );
var draggableInfo = document.getElementById( 'draggable_info' );
var droppableCopy = document.getElementById( 'droppable-copy' );
var droppableMove = document.getElementById( 'droppable-move' );

draggable.addEventListener( 'dragstart', function( event ) {
  event.dataTransfer.effectAllowed = 'all';
  event.dataTransfer.setData( 'text', 'Test' );
});

draggable.addEventListener( 'drag', function( event ) {
  draggableInfo.textContent = 'Drop effect: ' + event.dataTransfer.dropEffect;
});

draggable.addEventListener( 'dragend', function( event ) {
  draggableInfo.textContent = '';
});

droppableCopy.addEventListener( 'dragover', function( event ) {
  event.preventDefault();
  event.dataTransfer.dropEffect = 'copy';
});

droppableMove.addEventListener( 'dragover', function( event ) {
  event.preventDefault();
  event.dataTransfer.dropEffect = 'move';
});

#draggable,
#droppable-copy,
#droppable-move {
  margin: 10px;
  border: solid 1px;
  text-align: center;
  padding: 15px;
  width: 200px;
}
#draggable {
  cursor: move;
}

<div id="draggable" draggable="true">
  Drag me!
  <div id="draggable_info"></div>
</div>

<div id="droppable-copy">
  Drop here to copy
</div>

<div id="droppable-move">
  Drop here to move
</div>
&#13;
&#13;
&#13;

更新。如果使用dropEffect检查event.dataTransfer对象,我发现浏览器控制台会显示所需的console.log(event.dataTransfer)值。但如果您在一秒钟之后使用setTimeout检查此值,它仍然是none

0 个答案:

没有答案