简体   繁体   English

如何使用HTML5将元素拖放到新的div中?

[英]How to drag and drop element into new div using HTML5?

I'm trying to follow the guide here to make drag and drop work for my site, but I'm running across a problem catching the drop event. 我正在尝试按照此处的指南进行网站的拖放工作,但是遇到捕获drop事件的问题。

Pretty much what I want to do is allow users to drag an element into the div at the bottom, and once they actually drop it in, it will add it to that div. 我几乎想做的是允许用户将元素拖到底部的d​​iv中,一旦将其实际拖放到该元素中,它将添加到该div中。

Here is my fiddle . 这是我的小提琴 As you can see, the handleDrop function I created never gets called. 如您所见,我创建的handleDrop函数永远不会被调用。

I've also tried to add the eventListener "drop" on the individual elements instead of the one that they will be dropped into, but that doesn't seem to work either. 我还尝试将eventListener“ drop”添加到各个元素上,而不是将它们放入其中的元素,但这似乎也不起作用。 I've commented this out in the fiddle. 我已经在小提琴中对此进行了评论。 Any help? 有什么帮助吗?

Here's a Fiddle , and another approach. 这是小提琴 ,还有另一种方法。

HTML 的HTML

<img id="1" src="/" draggable="true" ondragstart="drag(event)" alt="Image 1"/>
<img id="2" src="/" draggable="true" ondragstart="drag(event)" alt="Image 2"/>
<img id="3" src="/" draggable="true" ondragstart="drag(event)" alt="Image 3"/>
<img id="4" src="/" draggable="true" ondragstart="drag(event)" alt="Image 4"/>
<img id="5" src="/" draggable="true" ondragstart="drag(event)" alt="Image 5"/>

<div id="playlist" ondrop="drop(event)" ondragover="allowDrop(event)">

</div>

CSS 的CSS

#playlist {
  position: absolute;
  top: 150px;
  left: 0;
  width: 960px;
  min-height:160px;
  background-color:#e5e5e5;
}
#playlist img {
  margin: 5px;
}
img {
  width: 150px;
  height: 90px;
  margin: 5px;
}

JS JS

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data=ev.dataTransfer.getData("Text");
  ev.target.appendChild(document.getElementById(data).cloneNode(true));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM