How to apply !important using .css()?

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

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

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


        
30条回答
  •  闹比i
    闹比i (楼主)
    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.

提交回复
热议问题