How to apply !important using .css()?

后端 未结 30 3064
情深已故
情深已故 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: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;' });
    

提交回复
热议问题