用jQuery添加!important [英] Adding !important with jQuery

查看:101
本文介绍了用jQuery添加!important的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个我无法完全解释的问题.

I ran into an issue that I can't quite explain.

我在该函数中编写了一个函数,向该元素添加了一些内联样式:

I wrote a function in in that function I was adding some inline styles to an element:

myEm.css({"margin":"0", "position":"fixed", "top":"50px", "left":"50px"});

它工作正常,但是我注意到该元素已经在CSS文件中设置了一些边距,并且使用了!important,所以我唯一可以覆盖的方法是将代码更改为

It worked fine, however I noticed that this element already had some margin set in a CSS file and it used !important, so the only way I would be able to overwrite is by changing my code to

myEm.css({"margin":"0 !important", "position":"fixed", "top":"50px", "left":"50px"});

但是,当我这样做时,整个margin属性将被删除.似乎有些奇怪,但是经过测试,我怀疑感叹号是罪魁祸首.我是否需要使用编码字符对其进行转义?我想念什么?

However, when I do that the entire margin attribute is dropped. Seems a bit odd, but after testing I suspect the exclamation mark is a culprit. Do I need to escape it somehow of use an encoded character? What am I missing?

推荐答案

最好的方法是使用margin !important创建新的CSS样式并将CSS添加到元素中.

Best way is to create a new CSS style with margin !important and add the CSS to the element.

CSS:

.zeroMargin { margin: 0 !important; }

,然后在 JS:

myEm.css({"position":"fixed", "top":"50px", "left":"50px"}).addClass('zeroMargin');

或者,您也可以使用cssText

myEm.css("cssText", "margin:0 !important;position:fixed;top:50px;left:50px;"});

这等效于设置该元素的style.cssText属性.因此,在这种情况下,您可能不需要!important.

This is equivalent to setting the style.cssText property of that element. So you may not need an !important in that case..

要保留,您可以使用以下功能,

To preserve you can use a function like below,

$('#cssTest').css('cssText', function(i, v) {
  return this.style.cssText + ';border-color: blue !important;';
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="cssTest" style="border: 1px solid red !important; width: 100px; height: 100px;"></div>

这篇关于用jQuery添加!important的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆