How do I get the height of a div's full content with jQuery?

前端 未结 6 2136
[愿得一人]
[愿得一人] 2020-11-29 02:57

I am trying to create my own scroll bars. I have tried most of the jquery scrollbar plugins and none of them seem to work for me, so I decided to create my own. I have an ov

6条回答
  •  醉梦人生
    2020-11-29 03:27

    If you can possibly help it, DO NOT USE .scrollHeight.

    .scrollHeight does not yield the same kind of results in different browsers in certain circumstances (most prominently while scrolling).

    For example:

    If you do

    console.log($('#outer').scrollHeight);

    you'll get 900px in Chrome, FireFox and Opera. That's great.

    But, if you attach a wheelevent / wheel event to #outer, when you scroll it, Chrome will give you a constant value of 900px (correct) but FireFox and Opera will change their values as you scroll down (incorrect).

    A very simple way to do this is like so (a bit of a cheat, really). (This example works while dynamically adding content to #outer as well):

    $('#outer').css("height", "auto");
    var outerContentsHeight = $('#outer').height();
    $('#outer').css("height", "350px");
    
    console.log(outerContentsHeight); //Should get 900px in these 3 browsers
    

    The reason I pick these three browsers is because all three can disagree on the value of .scrollHeight in certain circumstances. I ran into this issue making my own scrollpanes. Hope this helps someone.

提交回复
热议问题