2011-12-28 210 views
0

我写了这个功能,从右上角飞DIV到左下:的Javascript:复读功能不起作用

var myObj; 

function infly() { 
    myObj=document.getElementById('mydiv'); 
    myObj.style.right='0px'; 
    myObj.style.top='0px'; 
} 

function flyer() { 
    var x=parseInt(myObj.style.right); 
    var y=parseInt(myObj.style.top); 

    x+=1; 
    y+=1; 

    myObj.style.right=x+'px'; 
    myObj.style.top=y+'px'; 

} 

function repeat() 
{ 
setTimeout(flyer,5000) 
} 

和HTML代码是:

<body onLoad="infly()"> 

<div id="mydiv"> 
</div> 

<a href="" onClick="javascript:repeat()">Fly</a> 

... 
.. 
. 

repeat功能无法正常工作。当我每次点击删除此功能时,我的DIV都能正确地飞行。

我试用setInterval('fly();', 10);但没有成功。

感谢您的帮助。


更新:

我编辑的代码与正确的repeat功能,但还是不行。

回答

3

使用

setTimeout(fly,5000) 

代替

setTimeout("fly()","5000()") 
+0

我编辑的代码,但不能工作 – Nulled 2011-12-28 09:41:33

2

的setTimeout的第二个参数应为数字:

setTimeout(fly,5000) 

https://developer.mozilla.org/en/DOM/window.setTimeout

更新,贝特r不使用“fly()”:

替代语法中的代码是在延迟毫秒后要执行的代码字符串 。 (使用此语法不建议 同样的原因为使用eval())

+0

功能也应该只是阅读“飞”! – 2011-12-28 09:12:14

+0

@WillemMulder这是另一种优化。这个答案为这个问题提供了一个答案,并且包含了相关文档的链接。所以+1。 – 2011-12-28 09:13:06

+3

千万不要永远不要将字符串传递给setTimeout/setInterval或者需要对上下文进行EVALuated。这绝对是一种不好的做法 – fcalderan 2011-12-28 09:15:14

0

改变你的复读功能,看起来像这样

function repeat() { setTimeout("fly()",5000) } 
0

如果你想要的功能,不断不重复移动点击你需要调用repeat();在fly()结束时也是如此。 (如果是的话,你想完成什么...)

-2
<a href="javascript:void()" onclick="javascript:repeat()">Fly</a> 
setTimeout("fly()",5000) 
1

这里是代码,使分区飞。我设计了它,所以你可以看到它。你的代码只能调用传单一次,没有将位置设置为绝对的,div不会重新显示。

<script type="text/javascript"> 
    var K_CYCLES = 20; 
    var numcycles = 0; 

    function infly() { 
    myObj = document.getElementById('mydiv'); 
    myObj.style.right = '0px'; 
    myObj.style.top = '0px'; 

    } 

    function flyer() { 

    var x = parseInt(myObj.style.right); 
    var y = parseInt(myObj.style.top); 

    x += 10; 
    y += 10; 

    myObj.style.right = x + 'px'; 
    myObj.style.top = y + 'px'; 
    myObj.style.position = 'absolute'; 

    numcycles++; 

    if (numcycles <= K_CYCLES) 
    { 
     setTimeout("flyer()",1000); 
    } 
    } 

    function repeat() 
    { 
    flyer(); 
    } 
</script> 
</head> 
<body onLoad="infly()"> 

<div id="mydiv" style="width:50px; height: 50px; border: 1px solid red;"> 
</div> 

<input type="button" onClick="repeat()" value="fly"/> 
</body> 
+0

好的工作。但小问题。里面的重复函数'numcycles'应该设置为0,这样循环重复。 – tamilsweet 2011-12-29 03:23:18

0
<a href="javascript:void()" onclick="javascript:repeat()">Fly</a>