2011-12-24 96 views
0

昨天在CodeAcademy开始学习JavaScript,并决定我实际上可以编写代码。开玩笑。在网上浏览,发现有类似学习曲线的人,但没有任何答案解决了我的问题。即使在等待调用函数时,setTimeout也不会等待

在HTML中我有4个div。 3从左边距600px。 1的左边距400px。

还有4个按钮。当我按下一个按钮时,我试图让对应的div在一秒钟内向左滑动,直到剩下:400px。

我以前有divs跳(没有采取几乎看起来像滑动的步骤)到正确的位置,但已经打破了代码。好像setTimeout没有等待规定的时间。我做了一些在线调查,并认为在setTimeout完成时,保证金已经持续下降到最终的安息地点。

<html> 
<head><title></title> 

<script type="text/javascript" language="javascript"> 
//<![CDATA[ 

var stopPositionVisible = 400; 
var stopPositionHiding = 200; 


function slideIn(xslide){ 
    slidingDivInNow = document.getElementById(xslide); 

    if (parseInt(slidingDivInNow.style.left) > stopPositionVisible) { 
     slidingDivInNow.style.left = parseInt(slidingDivInNow.style.left) - 2 + "px"; 
     console.log(slidinDivInNow.style.left); 
    } 

    setTimeout(slideIn(xslide), 20); 
} 


//]]> 
</script> 
</head> 
<body> 

<a id="div0link" href="#" onclick="slideIn('d1');">Home</a> 
<a id="div1link" href="#" onclick="slideIn('d2');">page1</a> 
<a id="div2link" href="#" onclick="slideIn('d3'); ">page2</a> 
<a id="div3link" href="#" onclick="slideIn('d4'); ">page3</a> 

<div id="d1" style="position:absolute; left:400px; top:50px; background:black; color:white; width:200px">horizontally sliding div</div> 
<div id="d2" style="position:absolute; left:600px; top:60px; background:blue; color:white; width:200px">horizontally sliding div</div> 
<div id="d3" style="position:absolute; left:600px; top:70px; background:red; color:white; width:200px">horizontally sliding div</div> 
<div id="d4" style="position:absolute; left:600px; top:80px; background:green; color:white; width:200px">horizontally sliding div</div> 

</body> 
</html> 

谢谢你的任何见解。

+0

20毫秒几乎没有时间。不确定你的意思是“保证金已经持续下降”;该保证金不会自行下滑,你告诉它何时以及如何。 – 2011-12-24 16:38:46

+0

http://jsfiddle.net/mjaric/xRzXk/ – 2011-12-24 16:50:41

+0

谢谢@mjaric - 这是我最喜欢的网站 – 2011-12-24 17:27:29

回答

8
setTimeout(slideIn(xslide), 20); 

。您没有将slideIn函数传递给setTimeout,而是传递slideIn函数返回的值。你必须给一个函数传递给setTimeout,这意味着你会做这样的事情:

setTimeout(slideIn, 20); 

但是,这样一来,你没有得到的参数来传递。所以,你把它包装在一个匿名函数是这样的:

setTimeout(function(){ 
    slideIn(xslide); 
}, 20); 

你也可以给该函数的名称用于调试的目的是这样的:基本上

setTimeout(function slideTimeout(){ 
    slideIn(xslide); 
}, 20); 

,如果你的第一个参数运行typeof无论您传递给setTimeout还是setInterval,都应该返回'function'。你正在运行的将返回'undefined',因为你什么都没有返回。

3

将通话的功能容器

setTimeout(function() { slideIn(xslide); }, 20); 
+0

谢谢@ziesemer - 你们俩都给出了我在网上看到的最佳做法。当我做了什么建议,我没有看到任何成功。 slideIn函数似乎没有再次调用自己,或者它不会将xslide变量传递回自己。 – 2011-12-24 17:04:03

+0

在http://unitedicecream.com/films/slide.html# – 2011-12-24 17:07:47

+0

上发布了示例:'console.log(slidinginDivInNow.style.left);'将slidingDivInNow的拼写更正,并且它在Chrome中起作用。你可能想要放一个'if(console!=='undefined'){console.log(...); }'或者其他东西,所以你可以在IE中测试你的代码,等等... – ZagNut 2011-12-28 00:02:08

3

内的setTimeout你的函数调用被立即评估。你想这样的事情,而不是,返回,将一旦超时时间要执行的功能:立即调用slideIn功能

setTimeout(function(){slideIn(xslide)}, 20);