2010-09-02 47 views
4

我有一個簡單的功能噩夢!爲什麼這個javascript(jquery)函數看起來運行不正常?

我希望它:

  1. 讀一個div與現有內容的高度,它
  2. 更新與新的內容股利(供給函數)
  3. 讀出的高度的DIV應該是,但將其設置爲原始高度。
  4. 動畫div的高度以調整和適應新內容。

代碼如下:

// function to display status content by animating the height of the status message 
function slideStatus(content){ 

    // get current height 
    var status_origheight = $("#status-message").height(); 

    // insert new content 
    $("#status-message").html(content); 

    // get new height 
    var status_newheight = $("#status-message").height(); 

    // set the height to the orig value, hiding overflow content 
    $("#status-message").height(status_origheight).css("overflow","hidden"); 

    // animate the div to the new height 
    $("#status-message").animate({height:"+="+(status_newheight - status_origheight)+""}, 1000); 

} 

當我運行它,它似乎忽略了一個事實,即內容已經改變,只是使用原來的高度(因此也沒有動畫,因爲它認爲,高度沒有改變)。

請幫助,如果你可以!這讓我瘋狂。

回答

4

適合我。你的錯誤很可能在其他地方... http://jsfiddle.net/6aBfD/

UPDATE

http://jsfiddle.net/6aBfD/3/

但是,這隻能一次。問題在於你依靠一個元素來設置它自己的高度並從中讀取。但在第一次運行後,您將高度鎖定爲特定值。更新的鏈接有正確的工作方式,多次點擊。我添加了以下內容:

$("#status-message") 
    .css("overflow","visible") 
    .css("height", "auto"); 

現在,當您讀取高度時,它會是自然的高度。然後再次設置Oveflow和高度以將其鎖定回您想要的。

+1

Squeegy你的傳奇! 這樣做的技巧 - 溢出規則仍然是從上一次運行的div設置。 非常感謝! – Rob 2010-09-02 17:17:57

0

羅布,

請嘗試以下,而不是.height():

var status_origheight = $("#status-message").css('height');

+0

你是怎麼調用slideStatus函數的。這可能是問題所在。 – Adam 2010-09-02 17:01:48

相關問題