Add ondrop - ondragover to the new created element not working

被刻印的时光 ゝ 提交于 2019-12-02 17:47:35

问题


Every child-div is clicking. Within the divs there is a dragdiv, which can be dragged into a child div. Clicking the AddChild button creates a new child-div that is not an ondrop-ondragover. How can every new child-div get drag-div? I tried:

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>

来源:https://stackoverflow.com/questions/56181151/add-ondrop-ondragover-to-the-new-created-element-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!