JS動態寫入樣式

script標籤內能夠經過document.write('<style>your style</style>')直接寫入樣式定義,而在外部js文件裏面,這種方式是被瀏覽器阻止的,解決方法以下:css

  1. 建立一個Style元素並添加到DOM裏面
var style = document.createElement('style');
document.body.appendChild(style);
if (style.styleSheet) {
    style.styleSheet.cssText = 'css樣式定義';
} else {
    style.appendChild(document.createTextNode('css樣式定義'));
}

通常到第一步就能夠了,若是無效,可嘗試如下方法。瀏覽器

  1. 插入樣式定義
changeStyles(style.sheet, '.back', 'background-image:url(xxx.jpg)');
  1. changeStyle具體以下:
function changeStyles(sheet, selector, rules) {
    if ("insertRule" in sheet) {
        sheet.insertRule(selector + "{" + rules + "}", 0);
    } else if ("addRule" in sheet) {
        sheet.addRule(selector, rules, 0);
    }
}

**注意事項:**不能取已有的style標籤而後對其應用如上方法,經測試是無效的。app

參考連接測試

相關文章
相關標籤/搜索