简体   繁体   English

从 HTML 读取 css 文件抛出错误

[英]read css file from HTML throws error

I have the below code to read and append to a div tag.(I have a requirement to implement this.)我有以下代码可以读取并附加到 div 标签。(我需要实现这一点。)

var totalCss= "\n";
    var requiredSheets = ['test.css']; 
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var s = 0; s <= classes.length; s++) {
        var cssRules = document.styleSheets[s].cssRules ||
                document.styleSheets[s].rules || []; 
        for (var c = 0; c < cssRules.length; c++) {
            totalCss+= (cssRules[c].cssText + '\n');
        }
    }

Test.css is in the same folder of HTML. Test.css 在 HTML 的同一个文件夹中。

My test.css have the below properties.(this is just sample)我的 test.css 具有以下属性。(这只是示例)

.test triangle {

    stroke: #000;
    stroke-opacity: .75;
    shape-rendering: crispEdges;
}

.test square {
    stroke-opacity: .75;
}

.test circle {
    stroke-opacity: 0;
}

.test .line {
    fill: none; 

}

When I run the snippet I'm getting当我运行代码片段时,我得到了

No rules defined error没有规则定义错误

. . If the styles are embedded in the same html file, the properties are able to fetch by the code.如果样式嵌入在同一个 html 文件中,则属性可以通过代码获取。 But external files referenced in the html is not recognizing by the code.What may the cause?但是html中引用的外部文件没有被代码识别。可能是什么原因?

Sample样本

In this alert returns null.在此警报中返回空值。

Edit:编辑:

To my surprise the same code is working fine in Mozilla but showing cssrules null in chrome.令我惊讶的是,相同的代码在 Mozilla 中运行良好,但在 chrome 中显示 cssrules null。

There are multiple stylesheets with a document.一个文档有多个样式表。 So you have to loop all the stylesheets.所以你必须循环所有的样式表。

Below is the working example下面是工作示例

Update 1更新 1

Added ajax to get the external css linked with the page添加ajax获取与页面链接的外部css

 var style = "\\n"; for (var s = 0; s < document.styleSheets.length; s++) { var cssRules = document.styleSheets[s].cssRules || document.styleSheets[s].rules || []; // IE support for (var c = 0; c < cssRules.length; c++) { style += (cssRules[c].cssText + '\\n'); } } console.log(style); //Request for each external css $("link").each(function() { if (this.href) { $.get(this.href, function(css) { console.log(css); }); } });
 .box { position: absolute; background-color: red; height: 10px; width: 10px; } #car, .car { position: absolute; background-color: red; height: 11px; width: 10px; } }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM