我很难应用这样的风格!重要的我尝试过:

$("#elem").css("width", "100px !important");

这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?

编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。

此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。


当前回答

我认为它工作正常,可以覆盖之前的任何其他CSS(this:DOM元素):

this.setAttribute('style', 'padding:2px !important');

其他回答

这是我遇到这个问题后所做的。。。

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');

我想你没有添加就尝试了!重要的

内联CSS(这是JavaScript添加样式的方式)覆盖样式表CSS。我很确定,即使样式表CSS规则有这种情况!重要的

另一个问题(可能是一个愚蠢的问题,但必须要问。):您正在尝试的元素是否显示:block;或显示:内联块;?

不知道你在CSS方面的专业知识。。。内联元素的行为并不总是如您所期望的那样。

此解决方案不覆盖以前的任何样式,它只应用您需要的样式:

var heightStyle = "height: 500px !important";
if ($("foo").attr('style')) {
  $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
else {
  $("foo").attr('style', heightStyle);
}

对于这个问题,我认为最简单、最好的解决方案是使用addClass()而不是.css()或.attr()。

例如:

$('#elem').addClass('importantClass');

在CSS文件中:

.importantClass {
    width: 100px !important;
}

此解决方案将保留所有计算的javascript,并将重要标记添加到元素中:可以这样做(例如,如果需要设置重要标记的宽度)

$('exampleDiv').css('width', '');
//This will remove the width of the item
var styles = $('exampleDiv').attr('style');
//This will contain all styles in your item
//ex: height:auto; display:block;
styles += 'width: 200px !important;'
//This will add the width to the previous styles
//ex: height:auto; display:block; width: 200px !important;
$('exampleDiv').attr('style', styles);
//This will add all previous styles to your item