0

私のページでは、ページに垂直スクロールバーがあるかどうかを検出したいのですが、ある場合は、スクロールバーの幅を検出する必要があります。これにより、体を幅だけ縮小して、サイドバーが位置を変更して非表示が表示されないようにすることができます。スクロールページからスクロールページへ。私は次の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
        }
    });

残念ながら、このコードは私には機能しません。誰かが私がどこで間違っているのか教えてもらえますか?

4

2 に答える 2

0

の幅を変更する必要はありませんbody。デフォルトでは、ウィンドウの幅の 100% であり、スクロールバーが表示されると調整されます。

ただし、何らかの理由で幅を 100% に設定できない場合は、まず、水平スクロールバーを無効にすると役立つかどうかを確認してください。

overflow-x: hidden;

それでもうまくいかない場合は、ここの関数を使用してスクロールバーの幅を取得します。次に、windowサイズ変更イベントをリッスンします。

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

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

$(window).resize(resize);​
于 2012-08-11T14:52:12.057 に答える
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

フィドル

于 2012-08-11T14:44:58.087 に答える