這裏的代碼,我想用它:的Javascript offsetLeft不起作用
if(e.keyCode==32)
{
var c=document.createElement("img");
c.src="http://findicons.com/files/icons/1075/scrap/300/aqua_ball_red.png";
c.id="ball";
c.style.top=down+"px";
document.body.appendChild(c);
setTimeout(function move(){
c.style.left=1200+"px";
},200);
setTimeout(function kill(){
c.style.opacity=0;
},700);
}
};
它實際上是一個運動中的球,其按space.I後移動到一定COORDS需要映射它的座標時,它的moving.When我用這個:
var elem=document.getElementById("ball");
alert(elem.offsetLeft);
它什麼都不做,另外它使整個代碼if()
塊不working.My瀏覽器是Chrome瀏覽器
這裏有一個完整的代碼:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
#rocket
{
width:50px;
height:50px;
position:absolute;
top:0;left:0;
transition:top 0.4s, bottom 0.4s;
}
#ball
{
width:15px;
height:15px;
position:absolute;
transition:left 0.5s;
}
</style>
<script>
var down=0;
var up=0;
document.onkeydown=function(e){
e=e||window.event;
if(e.keyCode==40)
{
down=down+30;
document.getElementById("rocket").style.top=down+"px";
}
if(e.keyCode==38)
{
down=down-30;
document.getElementById("rocket").style.top=down+"px";
}
if(e.keyCode==32)
{
var c=document.createElement("img");
c.src="http://findicons.com/files/icons/1075/scrap/300/aqua_ball_red.png";
c.id="ball";
c.style.top=down+"px";
document.body.appendChild(c);
setTimeout(function move(){
c.style.left=1200+"px";
},200);
setTimeout(function kill(){
c.style.opacity=0;
},700);
}
};
document.onclick=function(e){
var y=e.pageY;
document.getElementById("rocket").style.top=y+"px";
down=y;
};
</script>
<img src="http://0.static.wix.com/media/a8b510_fc007f8eedd9f304c54ac6d374e3ee0b.gif_1024" id="rocket">
</body>
</html>
關於你提到的兩個定時器,一個更好的辦法是從第一個內啓動第二計時器。如果它們獨立運行(如你的代碼),它們之間的延遲是不可靠的。 –
每當空格鍵被擊中時,您都會創建這個'c' img,這意味着您將獲得重複的元素ID。 –
我們可以看到你的標記和CSS? – geedubb