How to apply !important using .css()?

后端 未结 30 2970
情深已故
情深已故 2020-11-21 07:06

I am having trouble applying a style that is !important. I’ve tried:

$(\"#elem\").css(\"width\", \"100px          


        
相关标签:
30条回答
  • 2020-11-21 07:37

    The safest workaround to this is to add a class and then do the magic in CSS :-), addClass() and removeClass() should do the work.

    0 讨论(0)
  • 2020-11-21 07:38

    I would assume you tried it without adding !important?

    Inline CSS (which is how JavaScript adds styling) overrides the stylesheet CSS. I'm pretty sure that's the case even when the stylesheet CSS rule has !important.

    Another question (maybe a stupid question but must be asked.): Is the element you are trying to work on display:block; or display:inline-block;?

    Not knowing your expertise in CSS... inline elements don't always behave as you would expect.

    0 讨论(0)
  • 2020-11-21 07:38

    I also discovered that certain elements or add-on's (like Bootstrap) have some special class cases where they do not play well with !important or other work-arounds like .addClass/.removeClass, and thus you have to to toggle them on/off.

    For example, if you use something like <table class="table-hover">the only way to successfully modify elements like colors of rows is to toggle the table-hover class on/off, like this

    $(your_element).closest("table").toggleClass("table-hover");

    Hopefully this work-around will be helpful to someone! :)

    0 讨论(0)
  • 2020-11-21 07:38

    I had the same problem trying to change a text color of a menu-item when "event". The best way I found when I had this same problem was:

    First step: Create, in your CSS, a new class with this purpose, for example:

    .colorw{ color: white !important;}
    

    Last step: Apply this class using the addClass method as follows:

    $('.menu-item>a').addClass('colorw');
    

    Problem solved.

    0 讨论(0)
  • 2020-11-21 07:39

    After reading other answers and experimenting, this is what works for me:

    $(".selector")[0].style.setProperty( 'style', 'value', 'important' );
    

    This doesn't work in IE 8 and under, though.

    0 讨论(0)
  • 2020-11-21 07:42

    I think I've found a real solution. I've made it into a new function:

    jQuery.style(name, value, priority);

    You can use it to get values with .style('name') just like .css('name'), get the CSSStyleDeclaration with .style(), and also set values - with the ability to specify the priority as 'important'. See this.

    Demo

    var div = $('someDiv');
    console.log(div.style('color'));
    div.style('color', 'red');
    console.log(div.style('color'));
    div.style('color', 'blue', 'important');
    console.log(div.style('color'));
    console.log(div.style().getPropertyPriority('color'));
    

    Here's the output:

    null
    red
    blue
    important
    

    The Function

    (function($) {    
      if ($.fn.style) {
        return;
      }
    
      // Escape regex chars with \
      var escape = function(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
      };
    
      // For those who need them (< IE 9), add support for CSS functions
      var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
      if (!isStyleFuncSupported) {
        CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
          return this.getAttribute(a);
        };
        CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
          this.setAttribute(styleName, value);
          var priority = typeof priority != 'undefined' ? priority : '';
          if (priority != '') {
            // Add priority manually
            var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
                '(\\s*;)?', 'gmi');
            this.cssText =
                this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
          }
        };
        CSSStyleDeclaration.prototype.removeProperty = function(a) {
          return this.removeAttribute(a);
        };
        CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
          var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
              'gmi');
          return rule.test(this.cssText) ? 'important' : '';
        }
      }
    
      // The style function
      $.fn.style = function(styleName, value, priority) {
        // DOM node
        var node = this.get(0);
        // Ensure we have a DOM node
        if (typeof node == 'undefined') {
          return this;
        }
        // CSSStyleDeclaration
        var style = this.get(0).style;
        // Getter/Setter
        if (typeof styleName != 'undefined') {
          if (typeof value != 'undefined') {
            // Set style property
            priority = typeof priority != 'undefined' ? priority : '';
            style.setProperty(styleName, value, priority);
            return this;
          } else {
            // Get style property
            return style.getPropertyValue(styleName);
          }
        } else {
          // Get CSSStyleDeclaration
          return style;
        }
      };
    })(jQuery);
    

    See this for examples of how to read and set the CSS values. My issue was that I had already set !important for the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute.

    Compatibility

    For setting with the priority using the setProperty function, This Article says there is support for IE 9+ and all other browsers. I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.

    0 讨论(0)
提交回复
热议问题