如何获得所有元素'坐标

时间:2016-05-31 09:52:46

标签: javascript dom

如果我知道元素的ID是"页脚" ,我可以用

 document.getElementById("footer").getBoundingClientRect();

获得"页脚"元素坐标。

有所有代码

var page = require('webpage').create();

page.open("https://stackoverflow.com/questions/18657615/how-to-render-an-html-element-using-phantomjs", function    (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        window.setTimeout(function () {
            //Heres the actual difference from your code...
            var bb = page.evaluate(function () {
                //return document.body.getBoundingClientRect();
                return document.getElementById("footer").getBoundingClientRect();    
            });

            page.clipRect = {
                top:    bb.top,
                left:   bb.left,
                width:  bb.width,
                height: bb.height
            };
           console.log(bb.top);
           console.log(bb.left);
           console.log(bb.width);
           console.log(bb.height);

            page.render('capture.png');
            phantom.exit();
        }, 200);
    }
});

结果是

4004.6875
0
1075
632.5

我必须知道page具有id为" footer"的元素。 如果有一个未知的网页,我不知道该网页的任何信息。 我如何获得所有元素坐标。

也许traversing the dom可以提供帮助,但我总是会遇到错误。我不知道如何正确合并代码。

1 个答案:

答案 0 :(得分:2)

让我们看看我们如何更改您找到的link中给出的代码:

function theDOMElementWalker(node) {
    if (node.nodeType == 1) {

        //console.log(node.tagName);

        node = node.firstChild;

        while (node) {
            theDOMElementWalker(node);
            node = node.nextSibling;
        }
    }
}

这可以很容易地扩展到将DOM“复制”到自定义表示中。例如:

var dom = page.evaluate(function(){
    var root = { children: [] };
    function walk(node, obj) {
        if (node.nodeType == 1) {

            obj.tagName = node.tagName;
            obj.boundingClientRect = node.getBoundingClientRect();

            node = node.firstChild;

            var childObj;
            while (node) {
                childObj = { children: [] };
                obj.children.push(childObj);
                walk(node, childObj);
                node = node.nextSibling;
            }
        }
    }

    walk(document.documentElement, root);

    return root;
});

console.log(JSON.stringify(dom, undefined, 4));

这里的想法是将DOM节点及其“简单”表示传递给walk函数。