简体   繁体   English

获取html文件中使用的所有css

[英]Getting all css used in html file

I have to get what are all the CSS styles used in a HTML file using JavaScript.我必须使用 JavaScript 获取 HTML 文件中使用的所有 CSS 样式。

<html>
    <head>
        <style type="text/css">
            body {
                border: 1px solid silver;
            }
            .mydiv{
                color: blue;
            }
        </style>
    </head>
    <body>
    </body>
</html>

If the above code is my HTML I have to write one JavaScript function inside the head which returns a string like this.如果上面的代码是我的 HTML,我必须在 head 内编写一个 JavaScript 函数,它返回这样的字符串。

body {
    border: 1px solid silver;
}
.mydiv {
    color: blue;
}

Is it possible to do?有可能吗?

For inline stylesheets, you can get the content out of the normal DOM like with any other element:对于内联样式表,您可以像处理任何其他元素一样从普通 DOM 中获取内容:

document.getElementsByTagName('style')[0].firstChild.data

For external, link ed stylesheets it's more problematic.对于外部link样式表,问题更大。 In modern browsers, you can get the text of every rule (including inline, linked and @imported stylesheets) from the document.styleSheets[].cssRules[].cssText property.在现代浏览器中,您可以从document.styleSheets[].cssRules[].cssText属性中获取每个规则的文本(包括内联、链接和@imported 样式表)。

Unfortunately IE does not implement this DOM Level 2 Style / CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces.不幸的是 IE 没有实现这个DOM Level 2 Style / CSS标准,而是使用它自己的 StyleSheet 和 CSSRule 接口的微妙不同版本。 So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original.因此,您需要一些嗅探和分支代码来在 IE 中重新创建规则,并且文本可能与原始文本不完全相同。 (In particular, IE will ALL-CAPS your property names and lose whitespace.) (特别是,IE 会将您的属性名称全部大写并丢失空格。)

var css= [];

for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
    var sheet= document.styleSheets[sheeti];
    var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
    for (var rulei= 0; rulei<rules.length; rulei++) {
        var rule= rules[rulei];
        if ('cssText' in rule)
            css.push(rule.cssText);
        else
            css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
    }
}

return css.join('\n');

Here's my solution :这是我的解决方案:

var css = [];
for (var i=0; i<document.styleSheets.length; i++)
{
    var sheet = document.styleSheets[i];
    var rules = ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
    if (rules)
    {
        css.push('\n/* Stylesheet : '+(sheet.href||'[inline styles]')+' */');
        for (var j=0; j<rules.length; j++)
        {
            var rule = rules[j];
            if ('cssText' in rule)
                css.push(rule.cssText);
            else
                css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
        }
    }
}
var cssInline = css.join('\n')+'\n';

In the end, cssInline is a textual list of all the steelsheets of the page and their content.最后, cssInline是页面所有钢板及其内容的文本列表。

Example :例子 :

/* Stylesheet : http://example.com/cache/css/javascript.css */
.javascript .de1, .javascript .de2 { -webkit-user-select: text; padding: 0px 5px; vertical-align: top; color: rgb(0, 0, 0); border-left-width: 1px; border-left-style: solid; border-left-color: rgb(204, 204, 204); margin: 0px 0px 0px -7px; position: relative; background: rgb(255, 255, 255); }
.javascript { color: rgb(172, 172, 172); }
.javascript .imp { font-weight: bold; color: red; }

/* Stylesheet : http://example.com/i/main_master.css */
html { }
body { color: rgb(24, 24, 24); font-family: 'segoe ui', 'trebuchet MS', 'Lucida Sans Unicode', 'Lucida Sans', sans-serif; font-size: 1em; line-height: 1.5em; margin: 0px; padding: 0px; background: url(http://pastebin.com/i/bg.jpg); }
a { color: rgb(204, 0, 51); text-decoration: none; }
a:hover { color: rgb(153, 153, 153); text-decoration: none; }
.icon24 { height: 24px; vertical-align: middle; width: 24px; margin: 0px 4px 0px 10px; }
#header { border-radius: 0px 0px 6px 6px; color: rgb(255, 255, 255); background-color: rgb(2, 56, 89); }
#super_frame { min-width: 1100px; width: 1200px; margin: 0px auto; }
#monster_frame { -webkit-box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; box-shadow: rgb(204, 204, 204) 0px 0px 10px 5px; border-radius: 5px; border: 1px solid rgb(204, 204, 204); margin: 0px; background-color: rgb(255, 255, 255); }
#header a { color: rgb(255, 255, 255); }
#menu_2 { height: 290px; }

/* Stylesheet : [inline styles] */
.hidden { display: none; }

From Mdn: 来自 MDN:

const allCSS = [...document.styleSheets]
  .map(styleSheet => {
    try {
      return [...styleSheet.cssRules]
        .map(rule => rule.cssText)
        .join('');
    } catch (e) {
      console.log('Access to stylesheet %s is denied. Ignoring...', styleSheet.href);
    }
  })
  .filter(Boolean)
  .join('\n');

Here is my solution:这是我的解决方案:

function getallcss() {
    var css = "", //variable to hold all the css that we extract
        styletags = document.getElementsByTagName("style");

    //loop over all the style tags
    for(var i = 0; i < styletags.length; i++)
    {
        css += styletags[i].innerHTML; //extract the css in the current style tag
    }

    //loop over all the external stylesheets
    for(var i = 0; i < document.styleSheets.length; i++)
    {
        var currentsheet = document.styleSheets[i];
        //loop over all the styling rules in this external stylesheet
        for(var e = 0; e , currentsheet.cssRules.length; e++)
        {
            css += currentsheet.cssRules[e].cssText; //extract all the styling rules
        }
    }

    return css;
}

It is based on @bobince's answer.它基于@bobince 的回答。

It extracts all the css from both the style tags and the external stylesheets.它从样式标签和外部样式表中提取所有 css。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 收集html文件中使用的所有js css和img资源 - collect all the js css and img resources used in a html file CSS 文件属性未在 HTML 代码中应用 - CSS File properties are not getting applied in The HTML code Ant任务:将HTML文件中使用的所有脚本复制到目录并进行压缩 - Ant Task: Copy all scripts used in HTML File to a directory and compress 是否有跨浏览器方法来获取所有元素的所有属性的已使用css值? - Is there a cross-browser method of getting the used css values of all properties of all elements? 获取 css 文件中包含的所有类/ID 的名称? - Getting the names of all classes / ids contained within a css file? 如何从一个HTML文件加载所有CSS和JS? - How to load all CSS and JS from one html file? 生成带有模板使用的所有CSS规则的内置angular index.html页面? - Generating a built angular index.html page with all the CSS rules used by the templates? 是否从特定样式表中识别特定HTML页面中使用的所有CSS ID和类? - Identify all css ID's and classes used in a particular HTML page from a specific stylesheet? 在HTML文件的主体或头部中创建的JS脚本可以直接在CSS代码中使用吗? - Can a JS script created in the body or head of an HTML file be used directly in CSS code? 获取一行以使用HTML / CSS显示 - Getting a line to display with HTML/CSS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM