dpa*_*nas 2 javascript css google-chrome-devtools
我想以编程方式从chrome开发人员工具中检索一组CSS类定义.实际上类似于右侧的样式选项卡中显示的内容.输入必须是类名,输出应该是其中定义的所有样式.
我知道getComputedStyle DOM方法,但是这并没有分成我需要的单独的类.
这种方法对我有用(stackoverflow.com/a/27527462/1023562):
/**
* Gets styles by a classname
*
* @notice The className must be 1:1 the same as in the CSS
* @param string className_
*/
function getStyle(className_) {
var styleSheets = window.document.styleSheets;
var styleSheetsLength = styleSheets.length;
for(var i = 0; i < styleSheetsLength; i++){
var classes = styleSheets[i].rules || styleSheets[i].cssRules;
var classesLength = classes.length;
for (var x = 0; x < classesLength; x++) {
if (classes[x].selectorText == className_) {
var ret;
if(classes[x].cssText){
ret = classes[x].cssText;
} else {
ret = classes[x].style.cssText;
}
if(ret.indexOf(classes[x].selectorText) == -1){
ret = classes[x].selectorText + "{" + ret + "}";
}
return ret;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
它允许您javascript在Chrome控制台中调用代码,如下所示:
console.log(getStyle('#heder_logo a'));
Run Code Online (Sandbox Code Playgroud)
得到这样的结果:
> #heder_logo a { width: 200px; height: 114px; display: block; }.
Run Code Online (Sandbox Code Playgroud)
我确实遇到了一些CSS文件的问题,这些文件不属于同一个域(它们是从CDN中提取的),但是该线程中有各种各样的提议,所以有些应该适合你.