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

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

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

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

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


当前回答

可能是这样的:

隐藏物

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

设置CSS

node.style.setProperty('width', '100px', 'important');

删除CSS

node.style.removeProperty('width');
OR
node.style.width = '';

其他回答

仅供参考,它不起作用,因为jQuery不支持它。2012年提交了一张罚单(#11173$(elem).css(“property”,“value!important”)失败),最终被关闭为WONTFIX。

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

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);
}

我们需要首先删除以前的样式。我使用正则表达式删除它。以下是更改颜色的示例:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }

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演示。

我还发现某些元素或插件(如Bootstrap)有一些特殊的类情况,它们不能很好地使用!重要的或其他解决方法,如.addClass/.removeClass,因此您必须打开/关闭它们。

例如,如果您使用类似<table class=“table hover”>的方法,成功修改行颜色等元素的唯一方法是打开/关闭table hover类,如下所示

$(your_element)最近(“table”).tggleClass(“table hover”);

希望这项工作对某人有帮助!:)