简体   繁体   中英

How can I check to see if a div contains an image element in JavaScript? (Not like a background image, like the element contained)

I have a fairly simple program which moves a picture of a house between 6 different tiles. The goal here is as follows:

  • When I drag a house on to an empty grass cell, I want the house to move to that cell. (This is already working.)
  • When I drag a house onto a cell containing a house, I want something special to happen. (Call a function)

Here's my code:

 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)); } function yeet() { alert("ekfui"); }
 .cell { border-radius: 10px; width: 100px; height: 100px; margin: 5px; padding: 5px; background-image: url("https://us.123rf.com/450wm/tuulijumala/tuulijumala1602/tuulijumala160200015/52473977-seamless-square-green-grass-texture-.jpg?ver=6"); }
 <!--What you actually see--> <div align="center"> <table> <tr> <td> <div id="gh" class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="http://worldartsme.com/images/free-house-clipart-1.jpg" draggable="true" ondragstart="drag(event)" id="drag1" width="100px" height="100px"> </div> </td> <td> <div class="cell" ondrop="drop(event); yeet();" ondragover="allowDrop(event)"></div> </td> <td> <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div> </td> </tr> <tr> <td> <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div> </td> <td> <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="http://worldartsme.com/images/free-house-clipart-1.jpg" draggable="true" ondragstart="drag(event)" id="drag2" width="100px" height="100px"> </div> </td> <td> <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div> </td> </tr> </table> </div>

No jQuery or libraries please

In your drop function, check if event currentTarget contains any img tags:

if (ev.currentTarget.querySelectorAll('img').length > 0) {
  alert('There\'s already a house there.');
} else {
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

https://jsfiddle.net/xmdkj0y4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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