2016-11-07 2 views
0

im пытается создать таблицу стилей с помощью JS и добавить некоторые правила, но это не сработает.Создать Styleshhet и insertRule/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;}"); 
} 

Извините im new in Js.

Может кто-нибудь сказать мне, почему это не работает?

ответ

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

GOT IT!

addRule/insertRule is not function of style! Его функция 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); 
} 
Смежные вопросы