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

$("#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 = '';

其他回答

这样做:

$("#elem").get(0).style.width= "100px!important";

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

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

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

例如:

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

在CSS文件中:

.importantClass {
    width: 100px !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)
const elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');

注:使用Chrome可能会返回错误,例如:

elem[0].style.removeAttribute不是函数

更改行以使用.removeProperty函数,如elem[0].style.removeProperty('width');解决了这个问题。