如何从HTMLStyleElement元素获取CSSStyleSheet对象

Fra*_*ger 7 html javascript css

是否可以document.styleSheets[0]从HTMLStyleElement(document.createElement('style'))获取CSSStyleSheet对象()?

我想动态地将css规则添加到未插入文档的<style>元素中.

Jon*_*een 6

这是可能从得到的CSSStyleSheet对象<style>元素。

var style = document.createElement('style');
document.head.appendChild(style);
var styleSheet = style.sheet // Will give you the associated CSSStyleSheet
Run Code Online (Sandbox Code Playgroud)

这只会工作后的<style>元素已经被附加到文件。

没有特别好的文档记录,并且很难通过在控制台中找到。


ken*_*bec 2

您可以在将样式元素添加到文档之前添加规则。

一些注意事项-

较旧的 IE 浏览器无法将子节点添加到样式元素,因此请为其分配元素的 styleSheet.csstext 属性。确保将新元素附加到文档的头部。

function addStyle(css, media1, title1){
    var el= document.createElement('style');
    el.type= 'text/css';
    if(media1) el.media= media1;
    if(title1) el.title= title1;
    if(el.styleSheet) el.styleSheet.cssText= css;//IE
    else{
        el.appendChild(document.createTextNode(css));
    }
    //return el without the next line if you want to append it later
    return document.getElementsByTagName('head')[0].appendChild(el);

}

var cs1= [
    '#yw_psq, #yw_psq h2{background-color: green; color: white;}',
    '#yw_psq_div{margin: 1ex; position: relative; text-align: center;}',
    '#ps_counter{color: white; margin: 1ex 0 0 0; text-align: center;}',
    '#pzsq_grid  button{cursor: pointer; font-size: 1.2em; width: 100%;}',
    '#delaySpan{font-weight: bold; margin-left: 1em;}'
]

addStyle(cs1.join('\n'),'screen','yw_psq');
Run Code Online (Sandbox Code Playgroud)