通过滚动查找所有元素

Finding all elements with a scroll

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

查找页面上所有滚动元素的最可靠、最有效的方法是什么?


目前,我正在考虑使用element.all()filter()来比较heightscrollHeight的属性值:

element.all(by.xpath("//*")).filter(function (elm) {
    return protractor.promise.all([
        elm.getAttribute("height"),
        elm.getAttribute("scrollHeight")
    ]).then(function (heights) { 
        return heights[1] > heights[0];
    });
});

但我不确定这种方法的正确性和性能。

这适用于水平和垂直滚动条。如果计算出的CSS允许您显示滚动条,那么诀窍是检测"与"是否过宽/过短。

var ElementsWithScrolls = (function() {
    var getComputedStyle = document.body && document.body.currentStyle ? function(elem) {
        return elem.currentStyle;
    } : function(elem) {
        return document.defaultView.getComputedStyle(elem, null);
    };
    function getActualCss(elem, style) {
        return getComputedStyle(elem)[style];
    }
    function isXScrollable(elem) {
        return elem.offsetWidth < elem.scrollWidth &&
            autoOrScroll(getActualCss(elem, 'overflow-x'));
    }
    function isYScrollable(elem) {
        return elem.offsetHeight < elem.scrollHeight &&
            autoOrScroll(getActualCss(elem, 'overflow-y'));
    }
    function autoOrScroll(text) {
        return text == 'scroll' || text == 'auto';
    }
    function hasScroller(elem) {
        return isYScrollable(elem) || isXScrollable(elem);
    }
    return function ElemenetsWithScrolls() {
        return [].filter.call(document.querySelectorAll('*'), hasScroller);
    };
})();
ElementsWithScrolls();

它将选择body标记中具有溢出和未溢出滚动的元素:

$('body *').filter(function() {
     return ($(this).scrollTop() != 0 || $(this).css('overflow') == 'scroll');
});