如何找出导致滚动条的元素

How to find out which element is causing a scrollbar

本文关键字:元素 滚动条 何找出      更新时间:2023-09-26

我有一个关于调试的问题。我想问你,我怎么能找出整个标记的哪个元素导致滚动条。任何一种方法都可以。我想过在开发人员工具中搜索overflow,但这并没有真正帮助我。

有谁知道我该如何解决这个问题?

您需要检查一些事项。首先,一个元素有一个溢出,会产生一个滚动条:overflow: scroll强制它们,overflow: auto在必要时显示它们。如果溢出是自动的,则可以根据实际高度检查其滚动高度。

function isScroller(el) {
    var isScrollableWidth, isScollableHeight, elStyle;
    elStyle = window.getComputedStyle(el, null); // Note: IE9+
    if (elStyle.overflow === 'scroll' ||
        elStyle.overflowX === 'scroll' ||
        elStyle.overflowY === 'scroll') {
        return true;        
    }
    if (elStyle.overflow === 'auto' ||
        elStyle.overflowX === 'auto' ||
        elStyle.overflowY === 'auto') {
        if (el.scrollHeight > el.clientHeight) {
            return true;
        }
        if (el.scrollWidth > el.clientWidth) {
            return true;
        }
    }
    return false;
}
var els = document.querySelectorAll('body *');
for (var i = 0, el; el = els[i]; i++) {
    if (isScroller(el)) {
        console.log(el);
    }
}

您可以在此处看到它(打开控制台): http://jsfiddle.net/rgthree/zfyhby1j/

请注意,某些触摸设备可能不会产生实际的"滚动条",除非在滚动时。这不会检测到这一点,而是检测到元素能够滚动。