[英]Using Javascript to move a div wont work
I have some javascript that should move my div element every 400 milliseconds. 我有一些JavaScript,应该每400毫秒移动一次div元素。 From debugging I have found that all my code works except when I go to move the div element. 通过调试,我发现我所有的代码都可以正常工作,除非我要移动div元素。 Ie, this code: 即,此代码:
block.style.left = xPos[index] + "px";
I am unsure why this code doesn't move my div? 我不确定为什么这段代码不会移动我的div? Should I use a different method (other than object.style.top etc.) to move my div? 我是否应该使用其他方法(而不是object.style.top等)移动div?
My java script: 我的Java脚本:
<script LANGUAGE="JavaScript" type = "text/javascript">
<!--
var block = null;
var clockStep = null;
var index = 0;
var maxIndex = 6;
var x = 0;
var y = 0;
var timerInterval = 400; // milliseconds
var xPos = null;
var yPos = null;
function moveBlock()
{
//alert( index ); // if you use this you will see my setInterval works fine
if ( index < 0 || index >= maxIndex || block === null || clockStep === null )
{
clearInterval( clockStep );
clockStep = null;
return;
}
block.innerHTML = "yellow"; // this works (just a debug test) so I know block points to the correct HTML element
block.style.left = xPos[index] + "px"; // this doesn't work
block.style.top = yPos[index] + "px";
index++;
}
function onBlockClick( blockID )
{
if ( clockStep !== null )
{
return;
}
block = document.getElementById( blockID );
index = 0;
x = parseInt( block.style.left, 10 );
y = parseInt( block.style.top, 10 );
xPos = new Array( x+10, x+20, x+30, x+40, x+50, x+60 );
yPos = new Array( y-10, y-20, y-30, y-40, y-50, y-60 );
clockStep = setInterval( "moveBlock()", timerInterval );
}
-->
</script>
The value of block.style.left
and block.style.top
is not set unless you use an absolutely-positioned div with preset values for both left and top (in fact, your array is filled with NaN
when I tested). 除非您使用绝对位置的div,并且为left和top设置预设值,否则未设置block.style.left
和block.style.top
值(实际上,在我测试时,数组用NaN
填充)。 For instance, the code works fine with a div defined like this: 例如,代码可以很好地与如下定义的div一起工作:
<div id="div1" style="position:absolute;left:100px;top:100px;
width:150px;height:150px;background-color:yellow;"
onclick="onBlockClick(this.id);">
HI
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.