[英]Using the self calling function in jQuery animate()
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script>
var m = -1;
function start(){
m++;
if(m<7){
$("#t"+m).animate({left: 950-m*50}, 2000, 'linear', (function(m){
if(m==6) $("#text_message").text("Well done!");
})(m));
}else{
clearTimeout(set);
}
set=setTimeout("start();", 1000);
}
</script>
</head>
<body onload="start();">
<div style="background: gray; width: 1000px; height: 50px; position: absolute; left: 0px; top: 0px;">
<div id="t6" style="width: 50px; height: 50px; background: red; position: absolute; left: 0px; top: 0px;"></div>
<div id="t5" style="width: 50px; height: 50px; background: orange; position: absolute; left: 50px; top: 0px;"></div>
<div id="t4" style="width: 50px; height: 50px; background: yellow; position: absolute; left: 100px; top: 0px;"></div>
<div id="t3" style="width: 50px; height: 50px; background: lime; position: absolute; left: 150px; top: 0px;"></div>
<div id="t2" style="width: 50px; height: 50px; background: blue; position: absolute; left: 200px; top: 0px;"></div>
<div id="t1" style="width: 50px; height: 50px; background: indigo; position: absolute; left: 250px; top: 0px;"></div>
<div id="t0" style="width: 50px; height: 50px; background: purple; position: absolute; left: 300px; top: 0px;"></div>
</div>
<div id="text_message" style=" position: absolute; left: 0px; top: 50px;">Not yet!</div>
</body>
</html>
這是jQuery animate()
方法的簡單示例。
我正在嘗試將所有盒子移到右側。
但是我遇到的問題不是animate()
方法,而是text_message
。
我希望所有框完全移到右側后, text_message
顯示“ 做好! ”。
不幸的是,在所有框都完全移到右側之前,它盡早顯示“ 做好! ”。
我怎么解決這個問題? 使用自調用功能有什么問題嗎?
謝謝。
@MorKadosh提供的解決方案效果很好,但請注意將setTimeout方法移至函數的開頭或if子句中,因為您當前存在一個無限循環。
您調用其他的clearTimeout方法,但之后再設置一次...
您無需像創建該自調用函數那樣調用完整的回調。 相反,您可以使用this
來訪問函數范圍內的動畫元素:
$("#t"+m).animate({left: 950-m*50}, 2000, 'linear', function(){
var n = $(this).attr('id').split('t')[1];
if(n == 6)
$("#text_message").text("Well done!");
});
您可以在這里看到一個有效的示例: https : //jsfiddle.net/41gavzsx/1/
我為此找到了自己的解決方案! 再創建一個setTimeout
對我來說很好,應該花2秒,因為您在正確的舉動中做了2秒
function start(){
m++;
if(m<7){
$("#t"+m).animate({left: 950-m*50}, 2000, 'linear', (function(m){
if(m==6) setTimeout(success,2000);
})(m));
}else{
clearTimeout(set);
}
set=setTimeout("start();", 1000);
}
function success(){
$("#text_message").text("Well done!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.