I'm unable to inject a style with an “!important” rule

前端 未结 7 1509
星月不相逢
星月不相逢 2020-12-05 04:19

I tried to inject a style using this code:

document.body.style.color=\'green!important\';

Per the CSS cascade ref, by applying the !i

7条回答
  •  抹茶落季
    2020-12-05 04:39

    Use only this:

    document.body.style.color="green";
    

    you can not have to use important in this way. Anyway as Fatal pointed out, this will not work, when there is directly important rule in css stylesheet, that you need to override.

    In that way, you have to dynamicaly create stylesheet and ad it inside head:

    function addNewStyle(newStyle) {
       var styleElement = document.getElementById('styles_js');
       if (!styleElement) {
           styleElement = document.createElement('style');
           styleElement.type = 'text/css';
           styleElement.id = 'styles_js';
           document.getElementsByTagName('head')[0].appendChild(styleElement);
       }
       styleElement.appendChild(document.createTextNode(newStyle));
    }
    

    Then you can update style just like that

    addNewStyle('body {color:green !important;}')
    

提交回复
热议问题