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

前端 未结 7 1493
星月不相逢
星月不相逢 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:31

    i need to keep !important for the following code how to do

    <script> var size = $(window).width(); 
    if(size >="1900" && size <="2890"){
     $(document).ready(function(){ $(".myMove").click(function(){ $(".hqnblogo").animate({ left:'-22% ', top: '67%', height:'7%', }); $(".hqnbnaturalslogo").animate({ left: '86%', top: '20px', height:'7%', }); }); }); } </script>?
    
    0 讨论(0)
  • 2020-12-05 04:33
    element.style.cssText = 'color:green !important';
    

    should work for you.

    0 讨论(0)
  • 2020-12-05 04:36

    I would like to pose that it may not be working not so much due to any error in code (excepting the space) but more because modifying the body tag isn't a specific enough element, class, or what have you to create the desired effect.

    Like for instance the page text of a search result has a class of "st". all search results are each encapsulated in an <li> tag.

    So some code to such effect might look like this:

    var arr = document.getElementsByClassName('st');
    for(i=0; i<arr.length; i++){
        arr[i].style.color="green";
    }
    
    0 讨论(0)
  • 2020-12-05 04:37

    style.cssText is the only way to add !important.

    <script>
       document.body.style.cssText='color: red !important;'
    </script>
    
    0 讨论(0)
  • 2020-12-05 04:38

    Per the spec, if you want to set the priority, not just the value, you have to use setProperty, like so:

    document.body.style.setProperty ("color", "green", "important");
    
    0 讨论(0)
  • 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;}')
    
    0 讨论(0)
提交回复
热议问题