我做了一些研究,找到了一种在 JavaScript 中获取伪选择器样式的方法。我们可以这样做,如下所示。
cssRules = window.getMatchedCSSRules(node, 'first-line')
但是当我在 phantomJS 中使用它时,它会返回节点本身的 css 规则,忽略伪选择器的规则。
如何获取伪选择器的 css 规则?
示例:
HTML代码
<html>
<head>
<style>
#fl::first-line{
color : red;
}
#fl{
color : yellow;
}
</style>
</head>
<body>
<div id = 'fl'>Convert this</div>
<div id = 'data'></div>
</body>
JavaScript
var node = document.getElementById('data');
var target = document.getElementById('fl')
console.log(window.getMatchedCSSRules(target, 'first-line')[0].style.color);
在网络浏览器上我得到的输出为红色,但在 phantomJS 中我得到的输出为黄色。
最佳答案
这似乎没有在 PhantomJS 1.9.7 中实现,但在 PhantomJS 2.0.0 中按预期工作:
var page = require('webpage').create();
var url = 'http://example.com';
page.open(url, function(){
console.log(JSON.stringify(page.evaluate(function(){
document.head.innerHTML = "<style>body::first-line{color : red;}body{color : yellow;}</style>";
return {
parent: getMatchedCSSRules(document.querySelector("body")),
pseudo: getMatchedCSSRules(document.querySelector("body"), "first-line")
};
}), undefined, 4));
phantom.exit();
});
输出:
{
"parent": {
"0": {
"CHARSET_RULE": 2,
"FONT_FACE_RULE": 5,
"IMPORT_RULE": 3,
"MEDIA_RULE": 4,
"PAGE_RULE": 6,
"STYLE_RULE": 1,
"UNKNOWN_RULE": 0,
"WEBKIT_KEYFRAMES_RULE": 7,
"WEBKIT_KEYFRAME_RULE": 8,
"WEBKIT_REGION_RULE": 16,
"cssText": "body { color: yellow; }",
"parentRule": "",
"parentStyleSheet": "",
"selectorText": "body",
"style": {
"0": "color",
...
"clipRule": "",
"color": "yellow",
"colorInterpolation": "",
"colorInterpolationFilters": "",
"colorProfile": "",
"colorRendering": "",
"content": "",
...
"zoom": ""
},
"type": 1
},
"item": {},
"length": 1
},
"pseudo": {
"0": {
"CHARSET_RULE": 2,
"FONT_FACE_RULE": 5,
"IMPORT_RULE": 3,
"MEDIA_RULE": 4,
"PAGE_RULE": 6,
"STYLE_RULE": 1,
"UNKNOWN_RULE": 0,
"WEBKIT_KEYFRAMES_RULE": 7,
"WEBKIT_KEYFRAME_RULE": 8,
"WEBKIT_REGION_RULE": 16,
"cssText": "body::first-line { color: red; }",
"parentRule": "",
"parentStyleSheet": "",
"selectorText": "body::first-line",
"style": {
"0": "color",
...
"clipRule": "",
"color": "red",
"colorInterpolation": "",
"colorInterpolationFilters": "",
"colorProfile": "",
"colorRendering": "",
"content": "",
"counterIncrement": "",
"counterReset": "",
"cssText": "color: red;",
...
"zoom": ""
},
"type": 1
},
"item": null,
"length": 1
}
}
注意 PhantomJS 不返回一个数组,而是一个带有整数键的对象,所以你需要这样访问它:
getMatchedCSSRules(el, "first-line")["0"].style.color
代替
getMatchedCSSRules(el, "first-line")[0].style.color
关于javascript - 获取 PhantomJS 中节点的伪选择器样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164868/