Javascript offsetLeft不起作用

时间:2013-12-23 14:52:30

标签: javascript html

这是我想要使用它的代码:

   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);
   }
  };

它实际上是一个移动的球,在按下空格后移动到某些坐标。我需要在它移动时映射它的坐标。当我使用它时:

var elem=document.getElementById("ball");
alert(elem.offsetLeft);

它什么都不做,另外它使if()块中的整个代码无效。我的浏览器是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>

3 个答案:

答案 0 :(得分:1)

left属性仅影响position设置为relativeabsolutefixed的元素。

答案 1 :(得分:0)

对于css left属性,您必须提及position

CSS:

#ball
{
  position:absolute; 
}

答案 2 :(得分:-1)

在您想要获取position: relativeposition: absolute属性之前,为您的元素添加样式lefttop

以简单的方式尝试使用jQuery:

alert($('#ball').offset().left);

var elem=document.getElementById("ball");
alert(elem.style.left);