Access CSS file contents via JavaScript

后端 未结 6 773
伪装坚强ぢ
伪装坚强ぢ 2020-11-30 04:29

Is it possible to get the entire text content of a CSS file in a document? F.ex:




        
6条回答
  •  囚心锁ツ
    2020-11-30 05:20

    With that specific example (where the CSS is on the same domain as the page), you could read the file as text via ajax:

    $.ajax({
        url: "/path/to/file.css",
        dataType: "text",
        success: function(cssText) {
            // cssText will be a string containing the text of the file
        }
    });
    

    If you want to access the information in a more structured way, document.styleSheets is an array of the style sheets associated with the document. Each style sheet has a property called cssRules (or just rules on some browsers), which is an array of the text of each rule in the style sheet. Each rule has a cssText property. So you could loop through those, e.g.:

    $.each(document.styleSheets, function(sheetIndex, sheet) {
        console.log("Looking at styleSheet[" + sheetIndex + "]:");
        $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
            console.log("rule[" + ruleIndex + "]: " + rule.cssText);
        });
    });
    

    Live example - That example has one stylesheet with two rules.

提交回复
热议问题