6

我需要能够检测浏览器窗口上是否有滚动条(垂直和水平)。我一直在使用此代码,但它在 Firefox 5 中无法可靠运行。

JFL.GetScrollbarState = function () {
    var myWidth = 0;
    var myHeight = 0;
    if (document.documentElement && document.documentElement.clientWidth) {
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else {
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return ({
        vScrollbar: document.body.scrollHeight > myHeight,
        hScrollbar: document.body.scrollWidth > myWidth
    });
}

有没有更好的方法可以跨浏览器工作。我的浏览器目标是 Firefox 4-5、Chrome、Safari 4+、Opera 10+。

如果您对为什么我需要知道是否有滚动条感兴趣,那是因为我有一些旋转的 CSS3 过渡(由于它们旋转的性质)可能暂时超出当前文档大小的边缘(从而使文档暂时较大)。如果最初没有滚动条,CSS3 过渡可能会导致滚动条在过渡期间出现,然后在过渡完成后消失,从而导致难看的滚动条闪烁。如果我知道没有滚动条,我可以临时添加一个类,将溢出-x 或溢出-y 设置为隐藏,从而防止滚动条在 CSS3 过渡期间闪烁。如果滚动条已经存在,我不需要做任何事情,因为它们可能会移动一点,但它们不会在过渡期间打开/关闭。

如果一个人实际上不仅可以判断是否通常需要滚动条,而且可以判断它们是否真的存在,那么奖励积分。

4

3 回答 3

5

After running into flicker problems with the scrolling version proposed by David in some browsers (Safari and IE), I've settled on this code that does not have the flicker problem:

function getScrollBarState() {
    var result = {vScrollbar: true, hScrollbar: true};
    try {
        var root = document.compatMode=='BackCompat'? document.body : document.documentElement;
        result.vScrollbar = root.scrollHeight > root.clientHeight;
        result.hScrollbar = root.scrollWidth > root.clientWidth;
    } catch(e) {}
    return(result);
}

It's a derivative of what I was using and the general technique was referenced in the post that fanfavorite posted. It seems to work in every browser I've tried even in IE6. For my purposes, I wanted any failure to return that there was a scrollbar so I've coded the failure condition that way.

Note: this code does not detect if a scrollbar has been forced on or off with CSS. This code detects if an auto-scrollbar is called for or not. If your page might have CSS settings that control the scrollbar, then you can get the CSS and check that first.

于 2011-07-10T05:34:04.867 回答
2

你看过这个其他帖子吗?如何在 HTML iFrame 中检测滚动条的存在(使用 Javascript)?

于 2011-07-07T03:11:37.623 回答
1

这实际上很容易。这适用于每个现代浏览器:

// try scrolling by 1 both vertically and horizontally
window.scrollTo(1,1);

// did we move vertically?
if (window.pageYOffset != 0) {
 console.log("houston, we have vertical scrollbars");
}

// did we move horizontally?
if (window.pageXOffset != 0) {
 console.log("houston, we have horizontal scrollbars");
}

// reset window to default scroll state
window.scrollTo(0,0);
于 2011-07-07T04:12:50.833 回答