2012-10-17 171 views
2

我做了一個litle javascript。像這樣:Javascript功能延遲

content.css('height', contentHeight, function() { 
    alert("test"); 
    $("body").scrollTo("#main", 600); 
}); 

我想在設置內容高度後執行警報。但是我做錯了什麼?

回答

1

.css()功能是instantanious。

content.css('height', contentHeight); 
alert("test"); 
$("body").scrollTo("#main", 600); 
0

沒有'完成'處理程序等方法,如css()。它立即執行。

所以,你必須編寫的代碼如下:

content.css("height", contentHeight); 
alert("test"); 
$("body").scrollTo("#main", 600); 

但是,如果你需要設置高度後添加一些延遲,你可以使用setTimeout()

content.css("height", contentHeight); 
setTimeout(function() { 
    alert("test"); 
    $("body").scrollTo("#main", 600); 
}, 1000); // 1000 is number of milliseconds 
0

的功能jQuery的css方法意思是不同的:

content.css('height', function(){ 
    return contentHeight; 
}); 

內容是一個數組,代碼abo ve爲此數組中的所有元素設置高度。此功能的用法可能如下:

content.css('height', function(index){ 
    return index * contentHeight; 
}); 

在這種情況下,每個下一個元素的高度將按contentHeight值遞增。

0

使用動畫,完成時調用回調。

content.animate({ 
    height: contentHeight 
}, 0, function() { 
    alert("test"); 
    $("body").scrollTo("#main", 600); 
}); 
0

嘗試使用

content.animate(
    {height : 100}, 
    5000, 
    function() { 
     //Animation complete. 
     alert("test"); 
     $("body").scrollTo("#main", 600); 
    } 
);