2016-11-07 114 views
0

即時通訊創建一個樣式表與JS和附加一些規則,但它不會工作。創建樣式和插入規則/ addRule

if (style == null) { 
    var style = document.createElement('style'); 
    style.setAttribute('type', 'text/css'); 
    style.setAttribute('data-style', 13); 
    if (style.styleSheet) { 
    style.styleSheet.cssText = ''; 
    } else { 
    style.appendChild(document.createTextNode('')); 
    } 
    document.head.appendChild(style); 

} 
if (typeof style.insertRule === 'function') { 
    style.insertRule("main > section[data-y='0']{top: 200px;}"); 
} else if (typeof style.addRule === 'function') { 
    style.addRule("main > section[data-y='0']", "{top: 200px;}"); 
} 

對不起,即時通訊新的。

有人可以告訴我爲什麼這不會工作?

回答

0

我有類似的任務,我的例子:

$('head').append('<link rel="stylesheet" type="text/css" href="css/test.css">'); 
    var sheets = document.styleSheets; 
    console.log(sheets) //need to know number of my file, in my case e.g. it was 2 
    var sheet = document.styleSheets[2]; 
    //also you forgot add index in the end of next line 
    sheet.insertRule("body { background-color: #000; }", 1); 

它不是一個最好的例子,但它的工作對我來說 ,我發現RLY好文章關於此任務 https://davidwalsh.name/add-rules-stylesheets

0

得到它!

addRule/insertRule不是風格的函數!它是style.sheet的一個功能,我忘了設置索引,所以它應該是

if (typeof style.sheet.insertRule === 'function') { 
    style.sheet.insertRule("main > section[data-y='0']{top: 200px;}",0); 
} else if (typeof style.sheet.addRule === 'function') { 
    style.sheet.addRule("main > section[data-y='0']", "{top: 200px;}",0); 
}