简体   繁体   中英

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
  2. Update the div with the new content (supplied to the function)
  3. Read the height the div should be, but set it to the original height.
  4. Animate the div's height to adjust and fit the new content.

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/

UPDATE

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. 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.

Rob,

Try the following instead of .height():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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