How to apply !important using .css()?

后端 未结 30 2965
情深已故
情深已故 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: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} 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.

提交回复
热议问题