Access CSS file contents via JavaScript

后端 未结 6 772
伪装坚强ぢ
伪装坚强ぢ 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:28

    The closest you can get to obtaining the stylesheet without using ajax is to indeed iterate over all CSS rules and concatenate them into a string. This yields the original file with all comments and excess whitespace removed. Which makes sense, as the browser only needs to keep the parsed style sheet in memory, not the original file. It is only 3 lines of code:

    function css_text(x) { return x.cssText; }
    var file = document.getElementById('css');
    var content = Array.prototype.map.call(file.sheet.cssRules, css_text).join('\n');
    

提交回复
热议问题