我用 HTML5 创建了一个简单的拖放游戏。项目按应有的方式拖放,但是在放置时我希望它检查放置在答案框 div 中的图像是否符合 javascript 要求。
处理拖放事件的 Javascript:
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){
ev.dataTransfer.setData("content", ev.target.id);
}
function drop(ev){
ev.preventDefault();
var image = ev.dataTransfer.getData("content");
ev.target.appendChild(document.getElementById(image));
if($('#answer1').find('#target1').length == 1)
{
alert("CORRECT!");
}
}
可能会在 drop 时执行此操作,但没有任何反应。图片一开始就在一个div中,图片本身的ID是answer1
,正确答案框当然是target1
。
以下是用于拖放的 HTML:
<div id="answerBoxes">
<div id="target1" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="target2" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="target3" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
<div id="target4" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>
</div> <!-- end of answerBoxes -->
<div id="whatsWhatContent">
<div id="answers">
<div id="answer1Box" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="answer1" src="Images/Icons/FlowerAnswer.png" draggable="true" ondragstart="drag(event)" alt="Flower answer box draggable"/>
</div>
<div id="answer2Box" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="answer2" src="Images/Icons/StemAnswer.png" draggable="true"
ondragstart="drag(event)" alt="Stem answer box draggable">
</div>
<div id="answer3Box" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="answer3" src="Images/Icons/RootAnswer.png" draggable="true" ondragstart="drag(event)" alt="Root answer box draggable">
</div>
<div id="answer4Box" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="answer4" src="Images/Icons/LeafAnswer.png" draggable="true" ondragstart="drag(event)" alt="Leaf answer box draggable">
</div>
CSS 对于图像周围的 div:
#answer1Box
{
float:left;
width: 125px;
height: 40px;
}
应删除图像的答案框的 CSS:
#target1
{
width: 120px;
height: 38px;
background-color: white;
margin-top: 30px;
border-radius: 5px;
border: 2px solid black;
}
http://jsfiddle.net/fSUNX/完整的 CSS