下面的代码是为了在用户按下空格键时在屏幕上移动一个小的红色 div。在“拍摄”功能中,我创建了一个新的 div 并设置了超时,然后它将开始从“moveLazer”功能向上移动屏幕。
问题:如果你拍摄了几次,“lazerLifeCycle”变量会在一个 div 到达屏幕顶部时清除,但也会清除仍在移动但尚未到达顶部的第二个或第三个 div 的超时。据我所知,使用 setInterval 并不能解决问题。我知道它是因为 lazerLifeCycle 是全球性的,但我没有看到正确的方法。请帮忙!js和html如下。请注意,如果您想复制/粘贴并尝试,它们是 2 个不同的文件。在 Firefox 或 chrome 中运行它。它在 IE 中没有任何作用。
//level3.js
var lazerId = 1;
var init = function(){
var ship = document.getElementById('randRect');
ship.style.left = '700px';
ship.style.top = '300px';
}
document.onkeyup = function(e) {
if(e.keyCode == 37) {
moveLeft();
} else if(e.keyCode == 39){
moveRight();
} else if(e.keyCode == 32){
shoot();
}
}
var shoot = function(){
lazerId = lazerId + 1;
var ship = document.getElementById('randRect');
width = parseInt(ship.clientWidth);
xPos = parseInt(ship.style.left);
middle = ((xPos + (width/2)) - 3) + 'px'; //-3 is to center it i think
var lazer = document.createElement('div');
lazer.id = lazerId;
var body = document.getElementById('body');
body.appendChild(lazer);
lazer.style.position = 'absolute';
lazer.style.width = '7px';
lazer.style.height = '13px';
lazer.style.left = middle;
lazer.style.top = '287px';
lazer.style.backgroundColor = 'red';
lazerLifeCycle = setTimeout('moveLazer(' + lazerId.toString() + ');', 10);
}
var moveLazer = function(lazerElementId){
var lazer = document.getElementById(lazerElementId.toString());
var lazerTop = parseInt(lazer.style.top);
if( (lazerTop - 1) < 0){
lazer.style.top = '0px';
clearTimeout(lazerLifeCycle);
} else {
lazer.style.top = (lazerTop - 1) +'px'
lazerLifeCycle = setTimeout('moveLazer(' + lazerElementId.toString() + ');', 10);
}
}
var moveLeft = function(){
var ship = document.getElementById('randRect');
shipXPos = parseInt(ship.style.left);
if( (shipXPos - 15) < 0){
ship.style.left = 0+'px';
} else {
ship.style.left = shipXPos - 15+'px';
}
}
var moveRight = function(){
var ship = document.getElementById('randRect');
shipXPos = parseInt(ship.style.left);
if( (shipXPos + 15) > 1300){
ship.style.left = 1300+'px';
} else {
ship.style.left = shipXPos + 15+'px';
}
}
window.onload = init;
//level3.html
<html>
<head>
<title>random</title>
<style type="text/css">
.random{
position:absolute;
background: orange;
padding: 7px;
}
</style>
<script src="level3.js" type="text/javascript">
</script>
</head>
<body id="body">
<div id="randRect" class="random"><center><-- or --><center></div>
</body>
</html>