简体   繁体   English

如何将CSS内容加载为StyleSheet对象?

[英]How to load css content as a StyleSheet object?

I have a css content with xhr load as the following code, 我有一个带有xhr load的css内容,如下代码,

var xhr = new XMLHttpRequest();
xhr.open('GET', 'my.css');
xhr.onreadystatechange = function () {
    if (this.readyState == this.DONE) {
        xhr.onreadystatechange = null;
        var style = $('<style/>').html(this.responseText);

        // it will print a dom string in dev console.
        console.log(style[0]);
    }
};
xhr.send();

So far I only know how to load the css content via ajax , but I want to let the css content become a StyleSheet object, just like to access the document.styleSheets[n] , I can't find any methods to do this, is there a way to do this? 到目前为止,我只知道如何通过ajax加载css内容,但我想让css内容成为StyleSheet对象,就像访问document.styleSheets[n] ,我找不到任何方法来执行此操作,有没有办法做到这一点?

my question is not apply or insert the css rules to the document, my question is how to let the css content string become a StyleSheet object, https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet 我的问题不是对文档应用css规则或将css规则插入文档,我的问题是如何使css内容字符串成为StyleSheet对象, https://developer.mozilla.org/zh-CN/docs/Web/API/StyleSheet

I think you can do it as following: 我认为您可以按照以下步骤进行操作:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'my.css');
xhr.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) { //4=this.DONE

    xhr.onreadystatechange = null;

    //var style = $('<style/>').html(this.responseText);
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = this.responseText;
    document.getElementsByTagName('head')[0].appendChild(style);

    var cssSheet = style.sheet; //this is the StyleSheet object you need
    var rule = cssSheet.cssRules[0]; //first rule defined in my.css
    alert("first css rule: "+ rule.selectorText + " => " + rule.style.cssText); 
  }
};
xhr.send();

The main tip is to use the sheet property of the HTMLStyleElement . 主要技巧是使用HTMLStyleElementsheet属性。 it must be accessed only after you have append it to the document. 只有将其附加到文档后,才能对其进行访问。

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

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