如果我知道元素的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为“页脚”的元素。
如果存在未知网页,则我不知道该网页的任何信息。
我如何获得所有元素坐标。
也许traversing the dom可以帮助您,但我总是会出错。我不知道如何正确合并代码。
最佳答案
让我们看看如何更改您在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函数中。
关于javascript - 如何获得所有元素的坐标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37542420/