添加ondrop-ondragover到新创建的元素不起作用

时间:2019-05-17 06:58:33

标签: javascript drag-and-drop click dom-events

每个child-div都在单击。 div中有一个dragdiv,可以将其拖动到子div中。单击AddChild按钮将创建一个新的child-div,它不是ondrop-ondragover。每个新的child-div如何获得阻力div? 我尝试过:

y.addEventListener ('ondrop', function () {drag (ev)}, false);
y.addEventListener ('ondragover', function () {drag (ev)}, false);
<style>
#divs{
  width: 450px;
  height: 70px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}

#dragdiv{
  width: 50px;
  height: 50px;
  margin: 10px;
  float: left;
  background-color: green;
}

#parent{
  width: 450px;
  height: 270px;
  margin: 10px;
  padding: 10px;
  background-color: blue;
}

#child{
  width: 430px;
  height: 70px;
  margin: 10px;
  float: left;
  background-color: red;
}

</style>
<div  id="divs" ondrop="drop(event)" ondragover="allowDrop(event)" >
     <div id="dragdiv" draggable="true" ondragstart="drag(event)" ></div>
</div>

<button type="button" onclick="AddChild()" >Add Child</button>

<div  id="parent">
<div  id="child" ondrop="drop(event)" ondragover="allowDrop(event)" ></div>
</div>
<script>

var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId

for (var i = 0; i < divCount; i += 1) {

    div[i].onclick = function(e) {
        clickedDivId = this.id;
        event.stopPropagation();
        alert(this.id);
    };
} 

function AddChild(){ 
var y = document.createElement('div'); 
y.id = 'child'+(i+1); 
y.style.width = '430px';
y.style.height = '70px';
y.style.margin = '10px';
y.style.backgroundColor = 'red';
y.style.float = 'left';

document.getElementById("parent").appendChild(y); i+=1;
y.addEventListener('click', function (e) { event.stopPropagation(); 
clickedDivId = this.id; 
alert(this.id); }, false); } 
</script>

<script>
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));
}
</script>

0 个答案:

没有答案