合并 getCompatedStyle 并在 Greasemonkey 中评估
我需要将页面中具有特定字体的所有文本节点获取到数组。我尝试过......
textnodes = document.evaluate("//* [@style='font-family: foo;']//text()["
+ "not(ancestor::script) and not(ancestor::style)]", document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
但是
textnodes = document.evaluate("//* [@face='foo']//text()["
+ "not(ancestor::script) and not(ancestor::style)]", document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
这些不适用于由外部 CSS 文件设置样式的页面。看来 getComputedStyle() 是可行的方法。我认为我需要的是......
var tags = document.getElementsByTagName('*');
for (var i in tags) {
var style = getComputedStyle(tags[i], '');
if (style.fontFamily.match(/foo/i)) {
textnodes.push(tags[i]);
}
}
但是此方法中没有返回文本节点。无论如何,我可以使用 xpathvaluate() 和 getComputedStyle() 的混合或任何其他方式来实现此目的吗?
I need to get all the text nodes with a certain font-face in a page to an array. I tried..
textnodes = document.evaluate("//* [@style='font-family: foo;']//text()["
+ "not(ancestor::script) and not(ancestor::style)]", document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
and
textnodes = document.evaluate("//* [@face='foo']//text()["
+ "not(ancestor::script) and not(ancestor::style)]", document,
null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
But these does not work with pages that is styled by external CSS files. Seems getComputedStyle() is the way to go. I think what I need is something like..
var tags = document.getElementsByTagName('*');
for (var i in tags) {
var style = getComputedStyle(tags[i], '');
if (style.fontFamily.match(/foo/i)) {
textnodes.push(tags[i]);
}
}
But text nodes were not returned in this method. Is there anyway I can use a hybrid of xpath evaluate() and getComputedStyle() or any other way to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 jQuery。 jQuery 对于 GM 脚本要做的其他事情非常有用,而且它更加健壮并且具有跨浏览器能力。
(1) 将此行添加到 Greasemonkey 元数据部分,就在
// @include
指令之后:(请注意,您可能需要卸载然后重新安装脚本才能复制 jQuery。)
(2) 然后就可以使用这段代码来获取节点:
这会检查计算的样式,并在本例中返回以 Times New Roman 开头的节点。
您可以在 jsFiddle 上查看此代码的实际版本。
Use jQuery. jQuery will be dead useful for the other things your GM script will do, plus, it's much more robust and cross-browser capable.
(1) Add this line to the Greasemonkey metadata section, just after the
// @include
directive(s):(Note you may have to uninstall and then reinstall the script to get jQuery copied over.)
(2) Then you can use this code to get the nodes:
This checks the computed style, and in this case returns nodes that start with Times New Roman.
You can see a version of this code, in action, at jsFiddle.
一种简单的方法是查找所有文本节点:
循环遍历找到的每个 TextNode,然后可以查找其父级的计算样式。如果是该字体,您可以将 TextNode 推送到 textnodes。
One easy way to do is to find all text nodes:
Looping through each TextNode found, you can then look up its parent's computedStyle. If it's that font, you can then
push
the TextNode totextnodes
.