Javascript offsetLeft不';行不通
下面是我想使用它的代码:Javascript offsetLeft不';行不通,javascript,html,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); setTimeo
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>
#火箭
{
宽度:50px;
高度:50px;
位置:绝对位置;
顶部:0;左侧:0;
过渡:顶部0.4s,底部0.4s;
}
#球
{
宽度:15px;
高度:15px;
位置:绝对位置;
过渡:左0.5s;
}
var-down=0;
var-up=0;
document.onkeydown=函数(e){
e=e | | window.event;
如果(e.keyCode==40)
{
向下=向下+30;
document.getElementById(“rocket”).style.top=down+px;
}
如果(e.keyCode==38)
{
down=down-30;
document.getElementById(“rocket”).style.top=down+px;
}
如果(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;
文件.正文.附件(c);
setTimeout(函数移动(){
c、 样式左=1200+“像素”;
},200);
setTimeout(函数kill(){
c、 不透明度=0;
},700);
}
};
document.onclick=函数(e){
var y=e.pageY;
document.getElementById(“rocket”).style.top=y+“px”;
向下=y;
};
对于cssleft
属性,left
属性只影响将位置
设置为相对
、绝对
或固定的元素。对于cssleft
属性,您必须提到位置
CSS:
#ball
{
position:absolute;
}
在要获取元素的左属性或顶属性之前,先使用样式位置:相对或位置:绝对
指定元素
使用jQuery以简单的方式尝试以下操作:
alert($('#ball').offset().left);
或
关于两个计时器,更好的方法是从第一个计时器中启动第二个计时器。如果它们独立运行(如在您的代码中),它们之间的延迟不可靠。每次点击空格键时,您都会创建此c
img,这意味着您将获得重复的元素ID。我们可以看到您的标记和CSS吗??
var elem=document.getElementById("ball");
alert(elem.style.left);