ChatGPT解决这个技术问题 Extra ChatGPT

如何使用 .css() 应用 !important?

我在应用 !important 样式时遇到问题。我试过了:

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

什么都不做;没有应用任何宽度样式。是否有一种 jQuery 风格的方式来应用这种样式而不必覆盖 cssText (这意味着我需要先解析它,等等)?

编辑:我应该补充一点,我有一个带有 !important 样式的样式表,我试图用 !important 内联样式覆盖它,因此使用 .width() 等不起作用,因为它被我的外部 !important 样式覆盖。

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

值得注意的是,这实际上适用于 Chrome(至少对我而言),但不适用于 Firefox。
这也适用于 Chrome 17.x 和 Safari 5.1.1,但不适用于 FF 8.0。
在使用 JQuery 1.8.2 的 Chromium 20.0.x 上对我不起作用。
jQuery bug #11173 是关于在 jQuery 核心中修复 .css!important。该错误被关闭为“不会修复”。但是,该错误的测试用例不像这个问题中的那样具有限制性——测试用例没有它试图覆盖的内联 !important 样式。因此,该错误中建议的解决方法在这种情况下将不起作用。
Overriding !important with css or jquery 的可能重复项——虽然这个更老,投票率更高,但另一个得到了最清晰、最有价值的答案。

M
Makyen

该问题是由于 jQuery 不理解 !important 属性导致的,因此无法应用该规则。

您或许能够解决该问题,并通过 addClass() 引用它来应用规则:

.importantRule { width: 100px !important; }

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

或使用 attr()

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

不过,后一种方法会取消任何先前设置的内联样式规则。所以要小心使用。

当然,有一个很好的论点是@Nick Craver 的方法更容易/更明智。

上面的 attr() 方法稍作修改以保留原始 style 字符串/属性,并按照 falko 在评论中的建议进行了修改:

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });

我倾向于你的后一种方法,但令人难过的是,我可能最终不得不解析以前的 cssText,因为我不能丢弃它
啊,抱歉没听懂,有时候英文幽默超出了我的理解……:)
嵌套引号 ('"width: 100px !important"') 是怎么回事?这对我不起作用,但是当我删除内部引号时它起作用了。谢谢!
样式为空时的小修复: $('#elem').attr('style', function(i,s) { return (s||'') + 'width: 100px !important;' });
您应该添加@falko 的修复程序,因为在 Firefox 中,当当前样式为空时,您的最后一个片段会将样式设置为 'undefinedwidth: 100px !important;'
a
ashleedawg

我想我找到了解决办法。我已经把它变成了一个新功能:

jQuery.style(name, value, priority);

您可以使用它来像 .css('name') 一样通过 .style('name') 获取值,通过 .style() 获取 CSSStyleDeclaration,还可以设置值,并能够将优先级指定为 'important' .见this

例子

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));

示例输出:

null
red
blue
important

功能

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);

有关如何读取和设置 CSS 值的示例,请参阅 this。我的问题是我已经为我的 CSS 中的宽度设置了 !important 以避免与其他主题 CSS 冲突,但是我对 jQuery 中的宽度所做的任何更改都不会受到影响,因为它们将被添加到样式属性中。

兼容性

对于使用 setProperty 函数设置优先级,This Article 表示支持 IE 9+ 和所有其他浏览器。我尝试过使用 IE 8,但它失败了,这就是为什么我在我的函数中构建了对它的支持(见上文)。它可以在使用 setProperty 的所有其他浏览器上运行,但它需要我的自定义代码才能在 < 中运行。即 9。


你在其他浏览器上测试过吗?
还有几年前发布的jQuery.important plugin。我在生产中使用它只有一个小问题(请参阅他们的问题选项卡。
$( '.someclass' ).each(function () { this.style.setProperty( 'border', 'none', 'important' ); }); stackoverflow.com/questions/11962962/… 更简单、更清洁、更高效。
处理这个问题的唯一好方法是使用类,而不是直接样式注入。
@Richard,解决这个问题的唯一好方法是 not 在您的样式中使用 !important ,至少对于您将要使用 jQuery 更改的内容......只要它们是 < i>你的风格。如果您的代码在一个学生编写的页面中运行,该学生通过在每隔一种样式上打 !important 来解决他对特异性规则的无知问题,那么您迟早会首先撞到其中一个 !importants 中。
N
Nick Craver

您可以像这样使用 .width() 直接设置宽度:

$("#elem").width(100);

更新评论:你也有这个选项,但它会替换元素上的所有 css,所以不确定它是否更可行:

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

好的,我以 with 为例,我关心的是设置!important。
我还编辑了问题以更好地反映我的情况..基本上我有一个外部!重要的宽度设置为不好的东西,我必须覆盖内联。由于这个原因,width() 不起作用
@mkoryak - 更新了唯一的其他非类选项,不确定它是否适合您的情况。
但它将覆盖直接应用于元素的任何其他样式。 stackoverflow.com/a/11723492/491044 是最容易实现的。
防止 $('#elem').css('cssText', $('#elem').css('cssText')+'width: 100px !important'); 覆盖将其与前一个值连接
m
mkoryak
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');)解决了该问题。


这是最好的答案之一。简单而且有效。而且不需要太多解释。它只是普通的 JavaScript,除了 jQuery 选择器。 jQuery 不提供对“重要”的支持,因此使用常规 JS 是可行的方法
如果您想使用 Vanilla,只需制作 var = document.getElementById('elem'); 并在 elem 上执行样式方法(而不是 elem[0])。干杯。
在 vanilla JS 中,removeAttribute 不起作用。请执行下列操作。 var style = document.getElementById('elem'); style.removeProperty('width'); style.setProperty('width, '100px', 'important')
.removeAttribute 也有问题。它似乎是一个 IE-only method。 @mcoenca 评论是对的; .removeProperty 工作正常。根据 MSDN,它是 IE9+
@Dejan,很抱歉回答得很晚,但这应该可行:elem.next().get(0).style...
C
Community

David Thomas’s answer 描述了一种使用 $('#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 demo


addStyleAttribute() 也可以修改为采用与 jQuery’s .css() 相同的参数。例如,它可以支持将 CSS 属性映射到它们的值。如果您这样做了,您基本上将重新实现 .css() 并修复 !important 错误但没有任何优化。
这对我来说效果很好,因为宽度是在 CSS 类中定义的,我需要使用基于浏览器窗口和内容的宽度计算的值来动态覆盖它。
N
Nate

在阅读了其他答案并进行了实验之后,这对我有用:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

不过,这在 IE 8 及以下版本中不起作用。


而且由于我们仍然必须支持 IE8(我们中的一些人,不幸的) - 这并不好。
P
Peter Mortensen

你可以这样做:

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

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


这样做的缺点是它会覆盖之前的 cssText - 所以你不能真正自由地使用它
无论如何,您可以使用 $("#elem").css("cssText", "+=;width: 100px !important;");
不要忘记您可以使用 tilda 字符串引号来包含变量:例如。 element.css({ 'cssText': `top: ${xTop}px !important` });
m
mkoryak

这些答案中的大多数现在都已过时,IE7 支持不是问题。

支持 IE11+ 和所有现代浏览器的最佳方法是:

const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');

或者,如果您愿意,您可以创建一个小型 jQuery 插件来执行此操作。这个插件在它支持的参数中与 jQuery 自己的 css() 方法非常匹配:

/**
 * Sets a CSS style on the selected element(s) with !important priority.
 * This supports camelCased CSS style property names and calling with an object 
 * like the jQuery `css()` method. 
 * Unlike jQuery's css() this does NOT work as a getter.
 * 
 * @param {string|Object<string, string>} name
 * @param {string|undefined} value
 */   
jQuery.fn.cssImportant = function(name, value) {
  const $this = this;
  const applyStyles = (n, v) => {
    // Convert style name from camelCase to dashed-case.
    const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
      return m1 + "-" + upper.toLowerCase() + m2;
    }); 
    // Loop over each element in the selector and set the styles.
    $this.each(function(){
      this.style.setProperty(dashedName, v, 'important');
    });
  };
  // If called with the first parameter that is an object,
  // Loop over the entries in the object and apply those styles. 
  if(jQuery.isPlainObject(name)){
    for(const [n, v] of Object.entries(name)){
       applyStyles(n, v);
    }
  } else {
    // Otherwise called with style name and value.
    applyStyles(name, value);
  }
  // This is required for making jQuery plugin calls chainable.
  return $this;
};
// Call the new plugin:
$('#elem').cssImportant('height', '100px');

// Call with an object and camelCased style names:
$('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});

// Call on multiple items:
$('.item, #foo, #bar').cssImportant('color', 'red');

Example jsfiddle here


这就是答案。无需检查其他答案
c
chharvey

您可以通过两种方式实现此目的:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");

实际上,.prop() function 是在 jQuery v1.6 中添加的,并且可以在 Chrome 中使用......这是从道具页面引用的:在 jQuery 1.6 之前,.attr() 方法有时会在检索某些属性时考虑属性值,这可能导致不一致的行为。从 jQuery 1.6 开始,.prop() 方法提供了一种显式检索属性值的方法,而 .attr() 检索属性。
对于通用解决方案来说,这不是一个好主意。您可以使用它覆盖您现有的样式。
P
Peter Mortensen

无需考虑@AramKocharyan 答案的复杂性,也无需动态插入任何样式标签。

只需覆盖样式,但您不必解析任何内容,为什么呢?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

不能使用 removeProperty(),因为它不会删除 Chrome 中的 !important 规则。
不能使用 element.style[property] = '',因为它在 Firefox 中只接受驼峰式。

你可以用 jQuery 来缩短这个时间,但是这个 vanilla 函数可以在现代浏览器、Internet Explorer 8 等上运行。


P
Peter Mortensen

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

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

谢谢,这比自定义插件实现起来要简单得多(即使它可能会破坏其他内联样式)。
A
A J A Y

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

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

P
Peter Mortensen

如果它不是那么相关,并且由于您正在处理一个 #elem 元素,您可以将其 id 更改为其他内容并根据需要设置样式...

$('#elem').attr('id', 'cheaterId');

在你的 CSS 中:

#cheaterId { width: 100px;}

为什么要更改 id 以应用 css 而不是仅添加 css 类?
P
Peter Mortensen

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

例如:

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

在你的 CSS 文件中:

.importantClass {
    width: 100px !important;
}

由于宽度是在 JavaScript 中计算的,因此这并不能解决问题。
S
Sebastian Zartner

尝试使用 addClass() 函数,而不是使用 css() 函数:

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>

OP 写道,该属性的值是动态计算的,因此您的答案对他不起作用。
这个解决方案对我有用。我认为我没有原始海报的确切需求,但它确实适用于 css() 没有的地方。
这确实是一个问题的完全合理的解决方案……只是不是这个问题!
Á
Álvaro González

仅供参考,它不起作用,因为 jQuery 不支持它。 2012 年 (#11173 $(elem).css("property", "value !important") fails) 提交了一张票,最终以 WONTFIX 的形式关闭。


P
Peter Mortensen

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

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

当 cssText 方法正常工作时,不知道为什么有这么多解决方案将样式标签破解到元素上......例如$selector.css('cssText','margin-bottom: 0 !important')
P
Peter Mortensen

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

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

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


C
Community

可能看起来像这样:

缓存

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 = '';

P
Peter Mortensen

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

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

P
Peter Mortensen

像这样做:

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

S
Sebastian Luna

此解决方案将保留所有计算的 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

P
Peter Mortensen

三个工作示例

我也遇到过类似的情况,但是在与 .closest() 苦苦挣扎了很长时间之后,我使用了 .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/


我不会给你投反对票,但你应该选择用更兼容跨浏览器的东西替换 .indexOf() 函数。而是使用 .match().test() 而不是 .indexOf()
为什么 var contents = 行中没有分号?
T
Tim Cutting

它可能适合也可能不适合您的情况,但您可以在很多此类情况下使用 CSS 选择器。

例如,如果您希望 .cssText 的第 3 个和第 6 个实例具有不同的宽度,您可以编写:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

或者:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}

匹配 .cssText 的第 3 和第 6 个实例。 :nth-of-type() 并没有按照您的想法去做。有关说明,请参见 here
很公平。我确实阅读了链接,但我不确定我是否理解您的观点。这是一个按预期工作的小提琴:jsfiddle.net/d2E4b
在您的小提琴中,您正在处理一系列 li 元素。它们都是相同的元素类型 li,这是选择器处理的内容。如果您要在同一个父项中混合不同的元素,则 :nth-of-type() 的行为会有所不同,尤其是在您将类选择器添加到混合中时。
P
Peter Mortensen

我假设您在不添加 !important 的情况下尝试过?

内联 CSS(这是 JavaScript 添加样式的方式)覆盖样式表 CSS。我很确定即使样式表 CSS 规则有 !important 也是如此。

另一个问题(可能是一个愚蠢的问题,但必须提出。):您尝试处理的元素是 display:block; 还是 display:inline-block;

不了解您在 CSS 方面的专业知识......内联元素并不总是像您期望的那样表现。


具有 !important 的 CSS 规则会覆盖所有内容,无论它们位于何处,唯一的例外是带有 !important 的内联样式将覆盖带有 !important 的样式表样式。这是我遇到的问题。有一个带有 !important 的样式表规则,我想覆盖它。更重要的是,我需要提供的值必须通过 JS 计算,所以我不能简单地更改样式表本身。
P
Peter Mortensen

我们可以使用 setProperty 或 cssText 将 !important 添加到使用 JavaScript 的 DOM 元素。

示例 1:

elem.style.setProperty ("color", "green", "important");

示例 2:

elem.style.cssText='color: red !important;'

A
Austin

我还发现某些元素或附加组件(如 Bootstrap)有一些特殊的类案例,它们不能很好地与 !important 或其他解决方法(如 .addClass/.removeClass)配合使用,因此您必须打开/关闭它们.

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

$(your_element).closest("table").toggleClass("table-hover");

希望这种解决方法对某人有所帮助! :)


P
Peter Mortensen

在“事件”时尝试更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现的最好方法是:

第一步:在您的 CSS 中为此目的创建一个新类,例如:

.colorw{ color: white !important;}

最后一步:使用 addClass 方法应用这个类,如下所示:

$('.menu-item>a').addClass('colorw');

问题解决了。


最佳答案,在我看来。最方便的一种。
谢谢@Siyah CSS 被很多人知道,但只有少数人理解,这很可悲,让一些程序员讨厌它哈哈
但是,如果您想使用 js 生成 CSS 值,例如 JS 中定义的颜色值,则不是。否则这很好。
为什么要在 js 中定义颜色?
P
Peter Mortensen

最安全的解决方法是添加一个类,然后在 CSS 中发挥作用 :-),addClass()removeClass() 应该可以完成工作。


R
Razan Paul

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

另一种方法是在 JavaScript 中动态创建和更新 CSS 类。为此,我们可以使用样式元素,并且需要使用样式元素的 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)