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

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

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

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

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


当前回答

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

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

其他回答

最安全的解决方法是添加一个类,然后在CSS中执行魔术:-),addClass()和removeClass()应该完成这项工作。

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');解决了这个问题。

三个工作示例

我也遇到过类似的情况,但在与.clost()进行了很长一段时间的斗争之后,我使用了.find()。

示例代码

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

可供替代的

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

工作:http://jsfiddle.net/fx4mbp6c/

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

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

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

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