通过overflow-y获取DIV的高度:滚动和更新内容

时间:2013-07-23 21:44:40

标签: jquery html height scrolltop

我有一个带溢出的常规空DIV:滚动;我通过类似$(elem).html(new_content);

的内容更新了div

现在这是我迷路的地方。我需要用新内容获得整个DIV的高度。通常它是通过ScrollTop设置完成的,但问题是$(elem)[0] .scrollHeight为零!!

如何解决此问题?

更新:我解决了这个问题。事实证明我的调用是在JQuery UI效果的回调函数中。回调函数应该使DIV可见。不知怎的,即使它是一个回调函数,DIV仍然不可见。所以,我必须将setTimeout设置为10 mS然后才能工作!!!

2 个答案:

答案 0 :(得分:0)

试试这个:

HTML:

<div></div>
<button>Button</button>

JS:

$("button").click(function () {
  //BEFORE HTML INSERTED, DIV IS EMPTY
  var height = $("div").scrollTop($("div"))[0].scrollHeight;
  console.log(height); //Outputs 1 (the starting div height)
  alert(height);

  //Add more <p>TEST4</p> and see that height SCROLLHEIGHT does indeed grow/update.
  $("div").html("<p>TEST</p><p>TEST2</p><p>TEST3</p>");
  $("div").height(50); // DIV starts at 1PX, and we set to 50PX so that we can see contents.

  //AFTER HTML INSERTED
  height = $("div").scrollTop($("div"))[0].scrollHeight;
  console.log(height); //Outputs 124 (the scroll height, notice the actual div height is 50)
  alert(height);
});

jsfiddle

答案 1 :(得分:0)

使用.height()并在每次更新div时检查

function newContent(){

    $('#test').html(new_content);
    var h = $('#test').height();
    console.log('new height is ' + h);

}

这是一个有效的jsfiddle:http://jsfiddle.net/F5K6H/