高效地获取元素的可见区域坐标

StackOverflow加载了关于如何检查元素在视口中是否真的可见的问题,但他们都寻求布尔答案。 我有兴趣获取元素的可见区域。

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

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

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

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

实施要求:

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

    当然,我可能很幼稚,并且为视口中的每个离散点调用elementFromPoint ,但是由于我遍历所有元素并且会经常这样做,所以性能至关重要。

    请指导我如何才能实现这一目标。

    免责声明:我很喜欢网络编程概念,所以我可能使用了错误的技术术语。

    进展:

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

  • 迭代所有元素,并将其垂直/水平线添加到坐标图(如果坐标位于视口内)。
  • 为每个“矩形”中心位置调用`document.elementFromPoint`。 矩形是来自步骤1的地图中的两个连续的垂直坐标和两个连续的水平坐标之间的区域。

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

    我执行的问题是:

  • 对于复杂的页面来说效率不高(可能需要2-4分钟才能完成大屏幕和Gmail收件箱)。
  • 它会为每个元素生成大量的矩形,这使得通过网络进行字符串化和发送效率低下,而且使用起来也很不方便(我希望以每个元素尽可能少的矩形结束)。

    尽我所知, 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>

    我不知道性能是否足够(尤其是在移动设备上),并且结果不像您请求的那样是一个矩形集,但您是否考虑使用位图来存储结果?

    注意一些元素可能具有3d css变换(例如,倾斜,旋转),一些元素可能具有边界半径,并且一些元素可能具有不可见的背景 - 如果您还想为这些“来自像素的元素”函数包含这些特征,矩形设置不能帮助你 - 但是位图可以容纳所有的视觉特征。

    生成位图的解决方案相当简单(我想...未经测试):

  • 创建可见屏幕大小的Canvas。
  • 迭代遍历所有元素,按z顺序排序,忽略隐藏
  • 对于每个元素在画布中绘制一个矩形,矩形的颜色是元素的标识符(例如,可以是增量计数器)。 如果您想要,您可以根据元素的视觉特征(倾斜,旋转,边框半径等...)修改矩形。
  • 将画布保存为无损格式,例如png而不是jpg
  • 发送位图作为屏幕上元素的元数据
  • 要查询哪个元素位于点(x,y)处,可以检查像素(x,y)处的位图颜色,并且颜色将告诉您该元素是什么。


    如果你可以放弃IE浏览器,这里有一个简单的例子:

    function getElementVisibleRect(el) {
      return new Promise((resolve, reject) => {
        el.style.overflow = "hidden";
        requestAnimationFrame((timeStamp) => {
          var br = el.getBoundingClientRect();
          el.style.overflow = "";
          resolve(br);
        });
      });
    }
    

    尽管如此,Promises很容易实现多元填充, requestAnimationFrame()工作原理可以追溯到IE 8。到2016年,您应该花费时间在较老的IE上给任何可怜的灵魂带来麻烦。

    链接地址: http://www.djcxy.com/p/83573.html

    上一篇: Efficiently get an element's visible area coordinates

    下一篇: angular2: is there a way to know when a component is hidden?