javascript - 高效获取元素可见区域坐标

标签 javascript jquery html css visibility

StackOverflow 是 loaded with questions关于如何检查一个元素是否真的在视口(viewport)中可见,但他们都在寻找一个 bool 值答案。我对获取元素的实际可见区域很感兴趣。

function getVisibleAreas(e) {
    ...
    return rectangleSet;
}

更正式地说 - 元素的可见区域是 CSS 坐标中的一组(最好是不重叠的)矩形, elementFromPoint(x, y) 如果点 (x, y) 包含在(至少)集合中的一个矩形中,将返回该元素。

在所有 DOM 元素(包括 iframe)上调用此函数的结果应该是一组非重叠区域集,其中 union 是整个视口(viewport)区域。

我的目标是创建某种视口(viewport)“转储”数据结构,它可以有效地返回视口(viewport)中给定点的单个元素,反之亦然 - 对于转储中的给定元素,它将返回一组可见区域。 (数据结构将传递给远程客户端应用程序,因此当我需要查询视口(viewport)结构时,我不一定能访问实际文档)。

实现要求:

  • 显然,实现应该考虑元素的 hidden状态,z-index 、页眉和页脚等
  • 我正在寻找一种适用于所有常用浏览器的实现,尤其是移动设备 - Android 的 Chrome 和 iOS 的 Safari。
  • 最好不要使用外部库。

    当然,我可以天真地调用elementFromPoint对于视口(viewport)中的每个离散点,但性能至关重要,因为我会遍历所有元素,并且会经常这样做。

    请指导我如何实现这个目标。

    免责声明:我对网络编程概念一窍不通,所以我可能使用了错误的技术术语。

    进度:

    我想出了一个实现。该算法非常简单:

    1. 遍历所有元素,并将它们的垂直/水平线添加到坐标图中(如果坐标在视口(viewport)内)。
    2. 为每个“矩形”中心位置调用 `document.elementFromPoint`。矩形是步骤 1 中 map 中两个连续的垂直坐标和两个连续的水平坐标之间的区域。

    这会产生一组区域/矩形,每个区域/矩形都指向一个元素。

    我的实现的问题是:

    1. 对于复杂的页面来说效率很低(对于真正的大屏幕和 gmail 收件箱可能需要 2-4 分钟)。
    2. 它会为每个元素生成大量矩形,这使得通过网络进行字符串化和发送时效率低下,而且使用起来也不方便(我希望最终得到一个具有尽可能少的集合每个元素尽可能长方形)。

    据我所知,elementFromPoint调用是一个花费大量时间并导致我的算法相对无用的......

    谁能提出更好的方法?

    这是我的实现:

    function AreaPortion(l, t, r, b, currentDoc) {
        if (!currentDoc) currentDoc = document;
        this._x = l;
        this._y = t;
        this._r = r;
        this._b = b;
        this._w = r - l;
        this._h = b - t;
    
        center = this.getCenter();
        this._elem = currentDoc.elementFromPoint(center[0], center[1]);
    }
    
    AreaPortion.prototype = {
        getName: function() {
            return "[x:" + this._x + ",y:" + this._y + ",w:" + this._w + ",h:" + this._h + "]";
        },
    
        getCenter: function() {
            return [this._x + (this._w / 2), this._y + (this._h / 2)];
        }
    }
    
    function getViewport() {
        var viewPortWidth;
        var viewPortHeight;
    
        // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
        if (
                typeof document.documentElement != 'undefined' &&
                typeof document.documentElement.clientWidth != 'undefined' &&
                document.documentElement.clientWidth != 0) {
            viewPortWidth = document.documentElement.clientWidth,
            viewPortHeight = document.documentElement.clientHeight
        }
    
        // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
        else if (typeof window.innerWidth != 'undefined') {
            viewPortWidth = window.innerWidth,
            viewPortHeight = window.innerHeight
        }
    
        // older versions of IE
        else {
            viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
            viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
        }
    
        return [viewPortWidth, viewPortHeight];
    }
    
    function getLines() {
        var onScreen = [];
        var viewPort = getViewport();
        // TODO: header & footer
        var all = document.getElementsByTagName("*");
    
        var vert = {};
        var horz = {};
    
        vert["0"] = 0;
        vert["" + viewPort[1]] = viewPort[1];
        horz["0"] = 0;
        horz["" + viewPort[0]] = viewPort[0];
        for (i = 0 ; i < all.length ; i++) {
            var e = all[i];
            // TODO: Get all client rectangles
            var rect = e.getBoundingClientRect();
            if (rect.width < 1 && rect.height < 1) continue;
    
            var left = Math.floor(rect.left);
            var top = Math.floor(rect.top);
            var right = Math.floor(rect.right);
            var bottom = Math.floor(rect.bottom);
    
            if (top > 0 && top < viewPort[1]) {
                vert["" + top] = top;
            }
            if (bottom > 0 && bottom < viewPort[1]) {
                vert["" + bottom] = bottom;
            }
            if (right > 0 && right < viewPort[0]) {
                horz["" + right] = right;
            }
            if (left > 0 && left < viewPort[0]) {
                horz["" + left] = left;
            }
        }
    
        hCoords = [];
        vCoords = [];
        //TODO: 
        for (var v in vert) {
            vCoords.push(vert[v]);
        }
    
        for (var h in horz) {
            hCoords.push(horz[h]);
        }
    
        return [hCoords, vCoords];
    }
    
    function getAreaPortions() {
        var portions = {}
        var lines = getLines();
    
        var hCoords = lines[0];
        var vCoords = lines[1];
    
        for (i = 1 ; i < hCoords.length ; i++) {
            for (j = 1 ; j < vCoords.length ; j++) {
                var portion = new AreaPortion(hCoords[i - 1], vCoords[j - 1], hCoords[i], vCoords[j]);
                portions[portion.getName()] = portion;
            }
        }
    
        return portions;
    }
    
  • 最佳答案

    尝试

    var res = [];
    $("body *").each(function (i, el) {
        if ((el.getBoundingClientRect().bottom <= window.innerHeight 
            || el.getBoundingClientRect().top <= window.innerHeight)
            && el.getBoundingClientRect().right <= window.innerWidth) {
                res.push([el.tagName.toLowerCase(), el.getBoundingClientRect()]);
        };
    });
    

    jsfiddle http://jsfiddle.net/guest271314/ueum30g5/

    参见 Element.getBoundingClientRect()

    $.each(new Array(180), function () {
        $("body").append(
        $("<img>"))
    });
    
    $.each(new Array(180), function () {
    $("body").append(
    $("<img>"))
    });
    
    var res = [];
    $("body *").each(function (i, el) {
    if ((el.getBoundingClientRect().bottom <= window.innerHeight || el.getBoundingClientRect().top <= window.innerHeight)
        && el.getBoundingClientRect().right <= window.innerWidth) {
        res.push(
        [el.tagName.toLowerCase(),
        el.getBoundingClientRect()]);
        $(el).css(
            "outline", "0.15em solid red");
        $("body").append(JSON.stringify(res, null, 4));
        console.log(res)
    };
    });
    body {
        width : 1000px;
        height : 1000px;
    }
    img {
        width : 50px;
        height : 50px;
        background : navy;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    关于javascript - 高效获取元素可见区域坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27146403/

    相关文章:

    jquery - Fancybox 导航箭头未显示

    html - 如何将旋转的元素定位在右侧的中间?

    javascript - 在 Pong 游戏中球穿过 Racket

    c# - 将 html 组件添加到页面的 AJAX 最佳实践

    javascript - Javascript-这是什么类型的HTML表格,您可以使用哪种类型的网络抓取技术?

    javascript - 为什么 onClick 事件在 html 中只工作一次?

    javascript - 带有透明三 Angular 形的下拉菜单(需要帮助)

    单击按钮时,JavaScript 函数将函数名称显示为未定义

    javascript - 将数据从数据库传递到 Rails 3.x 中的 Highcharts

    javascript - Angularjs 检查两个数组是否有不同的元素