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

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

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

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

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


当前回答

David Thomas的回答描述了一种使用$(“#elem”).attr(“style”,…)的方法,但警告称使用它将删除style属性中先前设置的样式。下面是一种使用attr()的方法,不会出现这种问题:

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

作为一项功能:

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

这是一个JS Bin演示。

其他回答

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

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

https://jsfiddle.net/xk6Ut/256/

另一种方法是在JavaScript中动态创建和更新CSS类。要做到这一点,我们可以使用style元素,并且需要为style元素使用ID,以便我们可以更新CSS类

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

...

  var cssText = '.testDIV{ height:' + height + 'px !important; }';
  writeStyles('styles_js', cssText)

David Thomas的回答描述了一种使用$(“#elem”).attr(“style”,…)的方法,但警告称使用它将删除style属性中先前设置的样式。下面是一种使用attr()的方法,不会出现这种问题:

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

作为一项功能:

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

这是一个JS Bin演示。

在头部附加样式的另一种方法:

$('head').append('<style> #elm{width:150px !important} </style>');

这将在所有CSS文件之后附加样式,因此它将比其他CSS文件具有更高的优先级,并将被应用。

您可以这样做:

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

使用“cssText”作为属性名,并将您希望添加到CSS中的任何内容作为其值。