代码之家  ›  专栏  ›  技术社区  ›  Chris Roberts

如何使用JQuery获得不包括水平滚动条的<DIV>的高度?

  •  4
  • Chris Roberts  · 技术社区  · 15 年前

    我正在编写一个jQuery插件,它使用了两个嵌套的<部门>元素。

    外部div具有固定的宽度,带有overflow:scroll,内部div(更宽)包含我想要滚动的内容。

    这一切都很好,除了我想使用一些JavaScript(带jQuery)来设置内部div的高度,使其与外部div的高度完全匹配,而不是水平滚动条的高度。

    现在我将它设置为外部div的高度,小于20像素。这种方式很管用,但它不会独立于浏览器,而且肯定是一种黑客行为!

    任何帮助都将不胜感激!

    2 回复  |  直到 15 年前
        1
  •  8
  •   BalusC    15 年前

    element.clientHeight . 在jQuery中,这类似于:

    var heightWithoutScrollbar = $('#outer')[0].clientHeight;
    
        2
  •  1
  •   Dan Herbert    15 年前

    我找到了一个可以 get the width of a scrollbar

    function getScrollBarWidth () {  
        var inner = document.createElement('p');  
        inner.style.width = "100%";  
        inner.style.height = "200px";  
    
        var outer = document.createElement('div');  
        outer.style.position = "absolute";  
        outer.style.top = "0px";  
        outer.style.left = "0px";  
        outer.style.visibility = "hidden";  
        outer.style.width = "200px";  
        outer.style.height = "150px";  
        outer.style.overflow = "hidden";  
        outer.appendChild (inner);  
    
        document.body.appendChild (outer);  
        var w1 = inner.offsetWidth;  
        outer.style.overflow = 'scroll';  
        var w2 = inner.offsetWidth;  
        if (w1 == w2) w2 = outer.clientWidth;  
    
        document.body.removeChild (outer);  
    
        return (w1 - w2);  
    };  
    

    编辑: http://jsbin.com/ejile3

    页面将提示滚动条的宽度。