我希望 img 文件在屏幕上移动并在单击时消失,在所有文件都消失后,会出现一个弹出窗口以显示完成。但是,我的代码只有一半有效,并且 img 文件停滞不前。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function runIt(me) {
$(me).css("top",Math.random()*800)
.animate({"left":"1200px"},Math.random()*3000+1500,function(){$(me).css("top",Math.random()*800)})
.animate({"left":"-150px"},Math.random()*3000+1500,function(){$(me).css("top",Math.random()*800);runIt(me)});
}
$(".target").each(function(){runIt($(this))});
score = 0;
function calcScore(me){
$(me).hide();
score++;
$("#message").html("You shot "+score);
if(score==8){
alert("You got all of them!");
}
}
</script>
<body>
<div id="container">
<div id="background">
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
<div class="target" onclick="calcScore(this)"><img src="images/bottle.png" width="80" height="80" alt=""/></div>
</div>
</div>
</body>
最佳答案
要修复它,只需在页面中添加此 css
.target {
position: absolute;
}
并将触发代码 $(".target").each(function(){runIt($(this))});
放入准备好的文档中,如下所示
$(document).ready(function(){
$(".target").each(function(){runIt($(this))});
})
关于javascript - 如何使用 JavaScript 移动游戏屏幕上的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738694/