2010-09-02 135 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

相关问题