Javascript 拖放:成功删除后删除拖动的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8269445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:51:30  来源:igfitidea点击:

Javascript Drag and Drop: removing dragged element following successful drop

javascripthtmldrag-and-drop

提问by lucas

I'm using the native drag and dropAPI in javascript. How can I remove a dragged element from the DOM following a successful drop?

我在 javascript 中使用本机拖放API。成功删除后,如何从 DOM 中删除拖动的元素?

  • I've tried listening to the dropevent, but this only gets fired on the element which is dropped onto and has no reference to the element being dragged.
  • I've tried listening to the dragendelement, but this doesn't let me know whether a drop was successful or not.
  • I'm trying to avoid storing the element being dragged in a global variable as this will cause problems if a drag occurs between different tabs or browsers.
  • 我试过监听放置事件,但这只会在被放置的元素上触发,并且没有引用被拖动的元素。
  • 我试过听dragend元素,但这并不能让我知道下降是否成功。
  • 我试图避免将被拖动的元素存储在全局变量中,因为如果在不同的选项卡或浏览器之间发生拖动,这会导致问题。

Here's an example: http://jsfiddle.net/KNG6n/3/

这是一个例子:http: //jsfiddle.net/KNG6n/3/

A list of letters which can be dragged into the box. When a letter's node is dropped on the box, I'd like it to be removed from the list (without effecting any other list items containing the same letter)

可以拖入框中的字母列表。当一个字母的节点被放到盒子上时,我希望它从列表中删除(不影响包含相同字母的任何其他列表项)

采纳答案by mdonovan2010

Listen for the dragend event and check the dropEffect variable of the dataTransfer object before doing anything with the dragged element:

在对拖动的元素执行任何操作之前,侦听 dragend 事件并检查 dataTransfer 对象的 dropEffect 变量:

htmlElement.addEventListener('dragend', function(event){
    if(event.dataTransfer.dropEffect !== 'none'){
        $(this).remove();
    }
});

回答by Daniel Ruf

Also take a look at this example: http://html5demos.com/drag

也看看这个例子:http: //html5demos.com/drag

var el = document.getElementById(e.dataTransfer.getData('Text'));

el.parentNode.removeChild(el);

var el = document.getElementById(e.dataTransfer.getData('Text'));

el.parentNode.removeChild(el);

回答by Ajit Khatke

You get the drop position of element in the dragendevent. You can find if an droppable element is present at that position.

您可以在dragend事件中获得元素的放置位置。您可以找到该位置是否存在可放置元素。

You can use document.elementFromPoint(x, y);

您可以使用 document.elementFromPoint(x, y);

回答by Rich O'Kelly

One way would be to assign this to a variable scoped outside of the dragstart, and use that element when dropped.

一种方法是将它分配给一个在 dragstart 范围之外的变量,并在放置时使用该元素。

See this fiddle.

看到这个小提琴。