简体   繁体   English

为什么这个javascript(jquery)函数似乎运行不正常?

[英]Why does this javascript (jquery) function seem to run out of order?

I'm having a nightmare with a simple function! 我有一个简单功能的噩梦!

I want it to: 我希望它:

  1. read the height of a div with existing content in it 读取包含现有内容的div的高度
  2. Update the div with the new content (supplied to the function) 使用新内容更新div(提供给函数)
  3. Read the height the div should be, but set it to the original height. 读取div的高度,但将其设置为原始高度。
  4. Animate the div's height to adjust and fit the new content. 动画div的高度以调整和适应新内容。

Code is as follows: 代码如下:

// 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);

}

When i run this, it appears to ignore the fact that the content has changed, and just use the original height (therefore do no animation as it thinks the height has not changed). 当我运行它时,它似乎忽略了内容已经改变的事实,并且只使用原始高度(因此不进行任何动画,因为它认为高度没有改变)。

Please help if you can!! 如果可以的话请帮忙!! It's driving me nuts. 这让我疯了。

Work for me. 为我工作。 Your bug is likely elsewhere... http://jsfiddle.net/6aBfD/ 您的错误可能在其他地方... http://jsfiddle.net/6aBfD/

UPDATE UPDATE

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

But that only works once . 但那只能工作一次 The problem is that you are relying on an element to set it's own height and read from that. 问题是你依靠一个元素来设置它自己的高度并从中读取。 But after the first run, you lock the height to a specific value. 但在第一次运行后,您将高度锁定到特定值。 The updated link has the correct working clode, click it multiple times. 更新的链接具有正确的工作clode,多次单击它。 I added the following: 我添加了以下内容:

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

Now when you read the height it will be it's natural height. 现在,当你读到高度时,它将是它的自然高度。 Then set the oveflow and height again later to lock it back down to what you want. 然后再次设置oveflow和height以将其锁定为您想要的。

Rob, 抢,

Try the following instead of .height(): 尝试以下代替.height():

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM