使用jQuery添加!important
我遇到了一个我无法解释的问题。
我在该函数中编写了一个函数,我在元素中添加了一些内联样式:
myEm.css({"margin":"0", "position":"fixed", "top":"50px", "left":"50px"});
它工作正常,但是我注意到这个元素已经在CSS文件中设置了一些边距并且它使用了!important,所以我能够覆盖的唯一方法是将我的代码更改为
myEm.css({"margin":"0 !important", "position":"fixed", "top":"50px", "left":"50px"});
但是,当我这样做时,整个margin属性被删除。 看起来有点奇怪,但经过测试我怀疑感叹号是罪魁祸首。 我是否需要以某种方式使用编码字符来逃避它? 我错过了什么?
最好的方法是创建一个带margin !important
的新CSS样式margin !important
并将CSS添加到元素中。
CSS:
.zeroMargin { margin: 0 !important; }
然后在JS中:
myEm.css({"position":"fixed", "top":"50px", "left":"50px"}).addClass('zeroMargin');
或者,您也可以使用cssText
完全使用JS
myEm.css("cssText", "margin:0 !important;position:fixed;top:50px;left:50px;"});
这相当于设置该元素的style.cssText
属性。 所以在这种情况下你可能不需要!important
..
为了保护你可以使用如下的function,
$('#cssTest').css('cssText', function(i, v) { return this.style.cssText + ';border-color: blue !important;'; });
用javascript函数这样做:
myEm[0].style.setProperty('margin', '0', 'important');
这是我在另一篇文章中发现的一个方便的技巧:
myEm.attr('style', function(i,s) { return s + 'margin: 0 !important;' });