我有一个当前工作的html / js代码,它允许我将4个对象移动到它们各自的DIV属性中,但是,我完全混淆了如何在用户拥有所有图像后获取警报弹出在他们各自的地方。如果有人有更好的方法或能指出我正确的方向,我会非常感激。这是我的jsfiddle链接:
https://jsfiddle.net/crizil/z2zd6bfk/1/
<body>
<img id="puzzle1" src="images/puzzle1.jpg" draggable="true" ondragstart="dragEvent(event)"
width="500" height="100">
<img id="puzzle2" src="images/puzzle2.jpg" draggable="true" ondragstart="dragEvent(event)"
width="500" height="100">
<img id="puzzle3" src="images/puzzle3.jpg" draggable="true" ondragstart="dragEvent(event)"
width="500" height="100">
<img id="puzzle4" src="images/puzzle4.jpg" draggable="true" ondragstart="dragEvent(event)"
width="500" height="100">
<div id="div1" ondrop="dropPic(event)" ondragover="dropEvent(event)" data- drop="puzzle1">
</div>
<div id="div2" ondrop="dropPic(event)" ondragover="dropEvent(event)" data- drop="puzzle2">
</div>
<div id="div3" ondrop="dropPic(event)" ondragover="dropEvent(event)" data- drop="puzzle3">
</div>
<div id="div4" ondrop="dropPic(event)" ondragover="dropEvent(event)" data- drop="puzzle4">
</div>
</body>
//allow ability to drop objects
function dropEvent(ev) {
ev.preventDefault();
}
//allow image dragging
function dragEvent(ev) {
ev.dataTransfer.setData('text', ev.target.id);
}
//drop image event
function dropPic(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
//make it to only drop in certain DIV attribute
if (ev.target.getAttribute('data-drop') == data)
ev.target.appendChild(document.getElementById(data));
}
如果我需要进一步澄清我想要做的事情,请告诉我,我希望有更好的方式来传达我想要做的事情。
答案 0 :(得分:0)
您可以添加一个计数器并检查它是否等于document.querySelectorAll('[data-drop]').length
:
var counter = 0;
function dropPic(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
//make it to only drop in certain DIV attribute
if (ev.target.getAttribute('data-drop') == data) {
ev.target.appendChild(document.getElementById(data));
if (++counter == document.querySelectorAll('[data-drop]').length) {
alert('all done');
}
}
}