我在应用 !important
样式时遇到问题。我试过了:
$("#elem").css("width", "100px !important");
这什么都不做;没有应用任何宽度样式。是否有一种 jQuery 风格的方式来应用这种样式而不必覆盖 cssText
(这意味着我需要先解析它,等等)?
编辑:我应该补充一点,我有一个带有 !important
样式的样式表,我试图用 !important
内联样式覆盖它,因此使用 .width()
等不起作用,因为它被我的外部 !important
样式覆盖。
此外,计算将覆盖先前值的值,因此我不能简单地创建另一个外部样式。
.css
和 !important
。该错误被关闭为“不会修复”。但是,该错误的测试用例不像这个问题中的那样具有限制性——测试用例没有它试图覆盖的内联 !important
样式。因此,该错误中建议的解决方法在这种情况下将不起作用。
该问题是由于 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;' });
我想我找到了解决办法。我已经把它变成了一个新功能:
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。
!important
,至少对于您将要使用 jQuery 更改的内容......只要它们是 < i>你的风格。如果您的代码在一个学生编写的页面中运行,该学生通过在每隔一种样式上打 !important
来解决他对特异性规则的无知问题,那么您迟早会首先撞到其中一个 !importants
中。
您可以像这样使用 .width()
直接设置宽度:
$("#elem").width(100);
更新评论:你也有这个选项,但它会替换元素上的所有 css,所以不确定它是否更可行:
$('#elem').css('cssText', 'width: 100px !important');
$('#elem').css('cssText', $('#elem').css('cssText')+'width: 100px !important');
覆盖将其与前一个值连接
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');
)解决了该问题。
var = document.getElementById('elem');
并在 elem 上执行样式方法(而不是 elem[0])。干杯。
var style = document.getElementById('elem'); style.removeProperty('width'); style.setProperty('width, '100px', 'important')
elem.next().get(0).style...
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
错误但没有任何优化。
在阅读了其他答案并进行了实验之后,这对我有用:
$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
不过,这在 IE 8 及以下版本中不起作用。
你可以这样做:
$("#elem").css("cssText", "width: 100px !important;");
使用“cssText”作为属性名称,并将您想要添加到 CSS 中的任何内容作为其值。
cssText
- 所以你不能真正自由地使用它
element.css({ 'cssText': `top: ${xTop}px !important` });
这些答案中的大多数现在都已过时,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');
您可以通过两种方式实现此目的:
$("#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()
检索属性。
无需考虑@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 等上运行。
这是我遇到这个问题后所做的......
var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
此解决方案不会覆盖任何以前的样式,它只会应用您需要的样式:
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);
}
如果它不是那么相关,并且由于您正在处理一个 #elem
元素,您可以将其 id 更改为其他内容并根据需要设置样式...
$('#elem').attr('id', 'cheaterId');
在你的 CSS 中:
#cheaterId { width: 100px;}
我对这个问题最简单和最好的解决方案是简单地使用 addClass() 而不是 .css() 或 .attr()。
例如:
$('#elem').addClass('importantClass');
在你的 CSS 文件中:
.importantClass {
width: 100px !important;
}
尝试使用 addClass()
函数,而不是使用 css()
函数:
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>
仅供参考,它不起作用,因为 jQuery 不支持它。 2012 年 (#11173 $(elem).css("property", "value !important") fails) 提交了一张票,最终以 WONTFIX 的形式关闭。
我们首先需要删除以前的样式。我使用正则表达式删除它。下面是一个改变颜色的例子:
var SetCssColorImportant = function (jDom, color) {
var style = jDom.attr('style');
style = style.replace(/color: .* !important;/g, '');
jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
$selector.css('cssText','margin-bottom: 0 !important')
在头部附加样式的另一种方法:
$('head').append('<style> #elm{width:150px !important} </style>');
这会在所有 CSS 文件之后附加样式,因此它将比其他 CSS 文件具有更高的优先级并被应用。
可能看起来像这样:
缓存
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 = '';
我认为它可以正常工作并且可以覆盖之前的任何其他 CSS(这个:DOM 元素):
this.setAttribute('style', 'padding:2px !important');
像这样做:
$("#elem").get(0).style.width= "100px!important";
此解决方案将保留所有计算的 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
三个工作示例
我也遇到过类似的情况,但是在与 .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 =
行中没有分号?
它可能适合也可能不适合您的情况,但您可以在很多此类情况下使用 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;}
li
元素。它们都是相同的元素类型 li
,这是选择器处理的内容。如果您要在同一个父项中混合不同的元素,则 :nth-of-type()
的行为会有所不同,尤其是在您将类选择器添加到混合中时。
我假设您在不添加 !important
的情况下尝试过?
内联 CSS(这是 JavaScript 添加样式的方式)覆盖样式表 CSS。我很确定即使样式表 CSS 规则有 !important
也是如此。
另一个问题(可能是一个愚蠢的问题,但必须提出。):您尝试处理的元素是 display:block;
还是 display:inline-block;
?
不了解您在 CSS 方面的专业知识......内联元素并不总是像您期望的那样表现。
我们可以使用 setProperty 或 cssText 将 !important
添加到使用 JavaScript 的 DOM 元素。
示例 1:
elem.style.setProperty ("color", "green", "important");
示例 2:
elem.style.cssText='color: red !important;'
我还发现某些元素或附加组件(如 Bootstrap)有一些特殊的类案例,它们不能很好地与 !important
或其他解决方法(如 .addClass/.removeClass
)配合使用,因此您必须打开/关闭它们.
例如,如果您使用 <table class="table-hover">
之类的方法,成功修改行颜色等元素的唯一方法是打开/关闭 table-hover
类,如下所示
$(your_element).closest("table").toggleClass("table-hover");
希望这种解决方法对某人有所帮助! :)
在“事件”时尝试更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现的最好方法是:
第一步:在您的 CSS 中为此目的创建一个新类,例如:
.colorw{ color: white !important;}
最后一步:使用 addClass 方法应用这个类,如下所示:
$('.menu-item>a').addClass('colorw');
问题解决了。
最安全的解决方法是添加一个类,然后在 CSS 中发挥作用 :-),addClass()
和 removeClass()
应该可以完成工作。
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)
不定期副业成功案例分享
'undefinedwidth: 100px !important;'
。