How to apply !important using .css()?

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

    David Thomas’s answer describes a way to use $('#elem').attr('style', …), but warns that using it will delete previously-set styles in the style attribute. Here is a way of using attr() without that problem:

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

    As a function:

    function addStyleAttribute($element, styleAttribute) {
        $element.attr('style', $element.attr('style') + '; ' + styleAttribute);
    }
    
    addStyleAttribute($('#elem'), 'width: 100px !important');
    

    Here is a JS Bin demo.

提交回复
热议问题