I have a fairly simple program which moves a picture of a house between 6 different tiles. The goal here is as follows:
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));
}
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.