检测垂直滚动和滚动条宽度并将宽度更改应用于正文

时间:2012-08-11 14:31:33

标签: javascript jquery asp.net

在我的页面中,我希望检测页面是否有垂直滚动条,如果是,则需要检测滚动条的宽度,这样我就可以减少宽度,从而防止我的侧边栏改变位置滚动页面的非滚动页面。 我有以下jQuery / Javascript代码:

        $(document).ready(function () {
        var parent, child, width;

        if (width === undefined) {
            parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body');
            child = parent.children();
            width = child.innerWidth() - child.height(99).innerWidth();
            parent.remove();
        }

        if ($("body").height() > $(window).height()) {
            //change width of body here
        }
    });

不幸的是,这段代码对我不起作用。有人可以让我知道我哪里出错吗?

2 个答案:

答案 0 :(得分:0)

(function($) {
    $.fn.ScrollBarWidth = function() {
        if (this.get(0).scrollHeight > this.height()) { //check if element has scrollbar
            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);
        }
    }
})(jQuery);

运行如此:

var scrollbarWidth = $('body').ScrollBarWidth();
console.log(scrollbarWidth);​ //prints the scrollbar width to the console

FIDDLE

答案 1 :(得分:0)

您不需要更改body的宽度。默认情况下,它是窗口宽度的100%,并在滚动条出现时进行调整。

但是,如果您因某些原因无法将宽度设置为100%,请先查看禁用水平滚动条是否有助于您:

overflow-x: hidden;

如果没有删除它,请使用here中的函数来获取滚动条的宽度。然后,收听window resize事件:

var $window = $(window),
    $body = $('body');

function resize() {
    if ($body.height() > $window.height()) {
        $body.width($body.width() - getScrollBarWidth());
    }
}

$(window).resize(resize);​