How to apply !important using .css()?

后端 未结 30 3030
情深已故
情深已故 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:42

    You can achieve this in two ways:

    $("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
    $("#elem").attr("style", "width: 100px !important");
    
    0 讨论(0)
  • 2020-11-21 07:42

    There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.

    Just overwrite style, but you don't have to parse anything, why would you?

    // Accepts the hyphenated versions (i.e. not 'cssFloat')
    function addStyle(element, property, value, important) {
        // Remove previously defined property
        if (element.style.setProperty)
            element.style.setProperty(property, '');
        else
            element.style.setAttribute(property, '');
    
        // Insert the new style with all the old rules
        element.setAttribute('style', element.style.cssText +
            property + ':' + value + ((important) ? ' !important' : '') + ';');
    }
    

    Can't use removeProperty(), because it won't remove !important rules in Chrome.
    Can't use element.style[property] = '', because it only accepts camelCase in Firefox.

    You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.

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

    Most of these answers are now outdated, IE7 support is not an issue.

    The best way to do this that supports IE11+ and all modern browsers is:

    const $elem = $("#elem");
    $elem[0].style.setProperty('width', '100px', 'important');
    

    Or if you want, you can create a small jQuery plugin that does this. This plugin closely matches jQuery's own css() method in the parameters it supports:

    /**
     * Sets a CSS style on the selected element(s) with !important priority.
     * This supports camelCased CSS style property names and calling with an object 
     * like the jQuery `css()` method. 
     * Unlike jQuery's css() this does NOT work as a getter.
     * 
     * @param {string|Object<string, string>} name
     * @param {string|undefined} value
     */   
    jQuery.fn.cssImportant = function(name, value) {
      const $this = this;
      const applyStyles = (n, v) => {
        // Convert style name from camelCase to dashed-case.
        const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
          return m1 + "-" + upper.toLowerCase() + m2;
        }); 
        // Loop over each element in the selector and set the styles.
        $this.each(function(){
          this.style.setProperty(dashedName, v, 'important');
        });
      };
      // If called with the first parameter that is an object,
      // Loop over the entries in the object and apply those styles. 
      if(jQuery.isPlainObject(name)){
        for(const [n, v] of Object.entries(name)){
           applyStyles(n, v);
        }
      } else {
        // Otherwise called with style name and value.
        applyStyles(name, value);
      }
      // This is required for making jQuery plugin calls chainable.
      return $this;
    };
    
    // Call the new plugin:
    $('#elem').cssImportant('height', '100px');
    
    // Call with an object and camelCased style names:
    $('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});
    
    // Call on multiple items:
    $('.item, #foo, #bar').cssImportant('color', 'red');
    
    

    Example jsfiddle here.

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

    The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule.

    You might be able to work around that problem, and apply the rule by referring to it, via addClass():

    .importantRule { width: 100px !important; }
    
    $('#elem').addClass('importantRule');
    

    Or by using attr():

    $('#elem').attr('style', 'width: 100px !important');
    

    The latter approach would unset any previously set in-line style rules, though. So use with care.

    Of course, there's a good argument that @Nick Craver's method is easier/wiser.

    The above, attr() approach modified slightly to preserve the original style string/properties, and modified as suggested by falko in a comment:

    $('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });
    
    0 讨论(0)
  • 2020-11-21 07:45

    The easiest and best solution for this problem from me was to simply use addClass() instead of .css() or .attr().

    For example:

    $('#elem').addClass('importantClass');

    And in your CSS file:

    .importantClass {
        width: 100px !important;
    }
    
    0 讨论(0)
  • 2020-11-21 07:46

    This solution will leave all the computed javascript and add the important tag into the element: You can do (Ex if you need to set the width with the important tag)

    $('exampleDiv').css('width', '');
    //This will remove the width of the item
    var styles = $('exampleDiv').attr('style');
    //This will contain all styles in your item
    //ex: height:auto; display:block;
    styles += 'width: 200px !important;'
    //This will add the width to the previous styles
    //ex: height:auto; display:block; width: 200px !important;
    $('exampleDiv').attr('style', styles);
    //This will add all previous styles to your item
    
    0 讨论(0)
提交回复
热议问题