I am having trouble applying a style that is !important
. I’ve tried:
我在应用一种很重要的风格上遇到了麻烦。我试过了:
$("#elem").css("width", "100px !important");
This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText
(which would mean I’d need to parse it first, etc.)?
这并没有;不适用任何宽度样式。是否有一种jquery式的方法来应用这种风格,而不必重写cssText(这意味着我需要首先解析它)?
Edit: I should add that I have a stylesheet with an !important
style that I am trying to override with an !important
style inline, so using .width()
and the like does not work since it gets overridden by my external !important
style.
编辑:我应该添加一个样式表和一个!重要的样式,我尝试用一个!重要的样式内联,所以使用.width()和like不工作,因为它被我的外部!重要的风格。
Also, the value that will override the previous value is computed, so I cannot simply create another external style.
另外,将会计算将覆盖先前值的值,因此我不能简单地创建另一个外部样式。
29 个解决方案
#1
292
I think I've found a real solution. I've made it into a new function:
我想我找到了一个真正的解决方法。我把它变成了一个新的函数:
jQuery.style(name, value, priority);
jQuery。风格(名称、价值优先);
You can use it to get values with .style('name')
just like .css('name')
, get the CSSStyleDeclaration with .style()
, and also set values - with the ability to specify the priority as 'important'. See this.
您可以使用它来获取带有.style('name')的值,就像.css('name')一样,使用.style()获得CSSStyleDeclaration,也可以设置值,它可以指定优先级为“重要”。看到这个。
Demo
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'));
Here's the output:
输出:
null
red
blue
important
The Function
(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);
See this for examples of how to read and set the CSS values. My issue was that I had already set !important
for the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute.
有关如何读取和设置CSS值的示例,请参见此示例。我的问题是,我已经设置了!在我的CSS中,为了避免与其他主题CSS的冲突,我对宽度很重要,但是我对jQuery宽度的任何更改都不会受到影响,因为它们会被添加到样式属性中。
Compatibility
For setting with the priority using the setProperty
function, This Article says there is support for IE 9+ and all other browsers. I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.
对于使用setProperty函数的优先级设置,本文表示支持IE 9+和所有其他浏览器。我已经尝试了ie8,但它失败了,这就是为什么我在我的函数中支持它(见上面)。它将使用setProperty在所有其他浏览器上工作,但它需要我的自定义代码在< ie9中工作。
#2
515
The problem is caused by jQuery not understanding the !important
attribute, and as such fails to apply the rule.
问题是由jQuery造成的,不理解!重要的属性,并不能应用规则。
You might be able to work around that problem, and apply the rule by referring to it, via addClass()
:
您可能可以解决这个问题,并通过addClass()来应用这个规则:
.importantRule { width: 100px !important; }
$('#elem').addClass('importantRule');
Or by using attr()
:
或使用attr():
$('#elem').attr('style', 'width: 100px !important');
The latter approach would unset any previously set in-line style rules, though. So use with care.
不过,后一种方法将取消任何以前设置的内嵌式规则。所以请小心使用。
Of course, there's a good argument that @Nick Craver's method is easier/wiser.
当然,有一个很好的论点,@Nick Craver的方法更容易/更明智。
The above, attr()
approach modified slightly to preserve the original style
string/properties:
上面的attr()方法稍微修改,以保留原来的样式字符串/属性:
$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
#3
135
You can set the width directly using .width()
like this:
可以直接使用.width()设置宽度:
$("#elem").width(100);
Updated for comments: You have this option as well, but it'll replace all css on the element, so not sure it's any more viable:
更新的评论:您也有这个选项,但是它将替换元素上的所有css,所以不确定它是否更可行:
$('#elem').css('cssText', 'width: 100px !important');
#4
62
var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
#5
51
David Thomas’s answer describes a way to use $('#elem').attr('style', …)
, but warns that using it will delete previously-set styles in the style
attribute. Here is a way of using attr()
without that problem:
David Thomas的回答描述了使用$('#elem')的方法。attr('style',…),但是警告说使用它将会删除样式属性中预先设置的样式。这里有一个使用attr()的方法,没有这个问题:
var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
As a function:
作为一个函数:
function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');
Here is a JS Bin demo.
这是一个JS Bin演示。
#6
27
After reading other answers and experimenting, this is what works for me:
在阅读了其他答案和实验之后,这就是我的工作:
$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
This doesn't work in IE 8 and under, though.
但这在IE 8和under中都不起作用。
#7
22
You can do this:
你可以这样做:
$("#elem").css("cssText", "width: 100px !important;");
Using "cssText" as the property name and whatever you want added to the css as it's value.
使用“cssText”作为属性名称,以及您想要添加到css中的任何内容。
#8
15
You can achieve this in two ways:
你可以通过以下两种方式实现:
$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
#9
12
Kinda late but here is what I did after encountering this problem...
有点晚了,但这是我遇到这个问题后做的…
var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style',origStyleContent+';width:150px !important');
#10
12
There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.
没有必要去关注@AramKocharyan的答案的复杂性,也不需要动态地插入任何样式标签。
Just overwrite style, but you don't have to parse anything, why would you?
只是覆盖风格,但你不需要解析任何东西,为什么?
//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' : '') + ';');
}
Can't use removeProperty()
because it wont remove !important
rules in Chrome.
Can't use element.style[property] = ''
because it only accepts camelCase in FireFox.
不能使用removeProperty(),因为它不会删除!不能使用元素。style[属性]= "因为它只接受FireFox中的camelCase。
You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, IE8 etc
您可能会用jQuery来缩短这个时间,但是这个函数将会在现代浏览器上运行,IE8等等。
#11
9
If it is not so relevant and since you're dealing with one element which is #elem
, you can change its id to something else and style it as you wish...
如果它不那么相关,并且因为您正在处理一个元素,那就是#elem,您可以将它的id更改为其他的,并按照您的意愿来样式化它。
$('#elem').attr('id','cheaterId');
and in your css:
和你的css:
#cheaterId { width: 100px;}
hope this helps, Sinan.
希望这有助于,斯楠。
#12
9
The easiest and best solution for this problem from me was to simply use addClass() instead of .css() or .attr().
对于这个问题,最简单和最好的解决方案是简单地使用addClass()而不是.css()或.attr()。
For example:
例如:
$('#elem').addClass('importantClass');
$(' # elem ').addClass(“importantClass”);
And in your css file:
在你的css文件中:
.importantClass {
width: 100px !important;
}
#13
9
This solution doesn't override any of the previous styles, it just applies the one you need:
这个解决方案不会覆盖任何之前的样式,它只适用于您需要的一个样式:
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);
}
#14
8
Instead of using the css()
function try the addClass()
function:
不要使用css()函数尝试addClass()函数:
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>
#15
6
We need first remove previous style. I remove using a regular. I send you a example for change color,...
我们需要先去掉之前的样式。我用一个普通的。我给你举个颜色改变的例子……
var SetCssColorImportant = function (jDom, color) {
var style = jDom.attr('style');
style = style.replace(/color: .* !important;/g, '');
jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
#16
6
An alternative way to append style in head
另一种附加样式的方法。
$('head').append('<style> #elm{width:150px !important} </style>');
this appends style after all your css files so it will have higher priority than other css files and will be applied
这个附加样式在所有css文件之后,所以它将比其他css文件有更高的优先级,并将被应用。
#17
6
May be look's like this:
可能是这样的:
cache
缓存
var node = $('.selector')[0]; OR var node = document.querySelector('.selector');
set css
设置css
node.style.setProperty('width', '100px', 'important');
remove css
删除css
node.style.removeProperty('width'); OR node.style.width = '';
#18
6
FYI, it doesn't work because jQuery doesn't support it. There was a ticket filed on 2012 (#11173 $(elem).css("property", "value !important") fails) that was eventually closed as WONTFIX.
FYI,它不起作用,因为jQuery不支持它。有一张2012年的机票(elem)。css(“属性”、“值!重要”)失败了,最终以“WONTFIX”关闭。
#19
5
Why not just doing like this:
为什么不这样做:
$("#elem").get(0).style.width= "100px!important";
#20
4
I would assume you tried it without adding important?
inline css (which is how js adds styling) overrides stylesheet css. I'm pretty sure that's the case even when the stylesheet css rule has !important.
我认为你试过没有添加重要的东西?内联css (js添加样式)覆盖了样式表css。我很确定,即使样式表css规则有!
Another question (maybe a stupid question but must be asked.): is the element you are trying to work on, is it display:block; or display:inline-block; ?
另一个问题(可能是一个愚蠢的问题,但必须要问。):你正在努力工作的元素是:block;或显示:inline-block;吗?
not knowing your expertise in CSS.. inline elements don't always behave as you would expect.
不知道你在CSS方面的专长。内联元素并不总是像您期望的那样表现。
#21
3
It may or may not be appropriate for your situation but you can use CSS selectors for a lot of these type of situations.
它可能适合您的情况,也可能不适合您,但是您可以使用CSS选择器来处理许多此类情况。
If, for example you wanted of the 3rd and 6th instances of .cssText to have a different width you could write:
例如,如果您希望.cssText的第3和第6实例具有不同的宽度,您可以编写:
.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}
Or:
或者:
.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
#22
3
I think it work ok and can overwrite any other css before(this: DOM element):
我认为它可以工作,并且可以在之前覆盖任何其他css(这是DOM元素):
this.setAttribute('style', 'padding:2px !important');
#23
2
I also discovered that certain elements or add-on's (like Bootstrap) have some special class cases where they do not play well with !important
or other work-arounds like .addClass/.removeClass
, and thus you have to to toggle them on/off.
我还发现,某些元素或附加组件(如Bootstrap)有一些特殊的类情况,它们不能很好地发挥作用!重要的或其他的工作方式。removeClass,因此你必须切换它们。
For example, if you use something like <table class="table-hover">
the only way to successfully modify elements like colors of rows is to toggle the table-hover
class on/off, like this
例如,如果您使用像
$(your_element).closest("table").toggleClass("table-hover");
$(your_element).closest .toggleClass(“表”)(“table-hover”);
Hopefully this work-around will be helpful to someone! :)
希望这样的工作对某人有帮助!:)
#24
2
we can use setProperty or cssText to add !important to dom element using java script.
我们可以使用setProperty或cssText来添加!使用java脚本对dom元素非常重要。
Eg1:
烤箱
elem.style.setProperty ("color", "green", "important");
Eg2:
Eg2:
elem.style.cssText='color: red !important;'
#25
2
I had the same problem trying to change a text color of a menu-item when "event". The best way i found when i had this same problem is:
当“事件”时,我试图更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现的最好的方法是:
1st step: Create, in your css, a new class with this purpose, for example:
第一步:在css中创建一个带有这个目的的新类:
.colorw{ color: white !important;}
last step: Apply this class using addClass method as follows:
最后一步:使用addClass方法应用这个类:
$('.menu-item>a').addClass('colorw');
Problem solved. Hope it helps!
问题解决了。希望它可以帮助!
#26
2
3 working examples
I had a similar situation, but I used .find() after struggling with .closest() for a long time with many variations.
我遇到过类似的情况,但我使用了。find()在与.最近的()进行了很长时间的变化。
The Example Code
// allows contains fuction 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 1000ms
});
Alternative
$( '.inner' ).each(function () {
this.style.setProperty( 'height', '50px', 'important' );
});
$('#out').find('.inner').css({ 'height': '50px'});
Up vote if you found any use, thanks.
如果你发现有用,请举手,谢谢。
Working: http://jsfiddle.net/fx4mbp6c/
工作:http://jsfiddle.net/fx4mbp6c/
#27
1
https://jsfiddle.net/xk6Ut/256/
https://jsfiddle.net/xk6Ut/256/
An alternative approach is dynamically creating and updating CSS class in JavaScript. To do that, we can use style element and need to employ the ID for the style element so that we can update the CSS class
另一种方法是动态地创建和更新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)
#28
1
The safest workaround to this is to add class then do the magic in CSS :-), addClass()
and removeClass()
should do the work.
最安全的方法是添加类,然后在CSS中执行魔法:-),addClass()和removeClass()应该完成工作。
#29
-6
Another easy method to solve this issue adding the style attribute:
另一个简单的方法来解决这个问题,添加样式属性:
$('.selector').attr('style', 'width:500px !important');
#1
292
I think I've found a real solution. I've made it into a new function:
我想我找到了一个真正的解决方法。我把它变成了一个新的函数:
jQuery.style(name, value, priority);
jQuery。风格(名称、价值优先);
You can use it to get values with .style('name')
just like .css('name')
, get the CSSStyleDeclaration with .style()
, and also set values - with the ability to specify the priority as 'important'. See this.
您可以使用它来获取带有.style('name')的值,就像.css('name')一样,使用.style()获得CSSStyleDeclaration,也可以设置值,它可以指定优先级为“重要”。看到这个。
Demo
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'));
Here's the output:
输出:
null
red
blue
important
The Function
(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);
See this for examples of how to read and set the CSS values. My issue was that I had already set !important
for the width in my CSS to avoid conflicts with other theme CSS, but any changes I made to the width in jQuery would be unaffected since they would be added to the style attribute.
有关如何读取和设置CSS值的示例,请参见此示例。我的问题是,我已经设置了!在我的CSS中,为了避免与其他主题CSS的冲突,我对宽度很重要,但是我对jQuery宽度的任何更改都不会受到影响,因为它们会被添加到样式属性中。
Compatibility
For setting with the priority using the setProperty
function, This Article says there is support for IE 9+ and all other browsers. I have tried with IE 8 and it has failed, which is why I built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.
对于使用setProperty函数的优先级设置,本文表示支持IE 9+和所有其他浏览器。我已经尝试了ie8,但它失败了,这就是为什么我在我的函数中支持它(见上面)。它将使用setProperty在所有其他浏览器上工作,但它需要我的自定义代码在< ie9中工作。
#2
515
The problem is caused by jQuery not understanding the !important
attribute, and as such fails to apply the rule.
问题是由jQuery造成的,不理解!重要的属性,并不能应用规则。
You might be able to work around that problem, and apply the rule by referring to it, via addClass()
:
您可能可以解决这个问题,并通过addClass()来应用这个规则:
.importantRule { width: 100px !important; }
$('#elem').addClass('importantRule');
Or by using attr()
:
或使用attr():
$('#elem').attr('style', 'width: 100px !important');
The latter approach would unset any previously set in-line style rules, though. So use with care.
不过,后一种方法将取消任何以前设置的内嵌式规则。所以请小心使用。
Of course, there's a good argument that @Nick Craver's method is easier/wiser.
当然,有一个很好的论点,@Nick Craver的方法更容易/更明智。
The above, attr()
approach modified slightly to preserve the original style
string/properties:
上面的attr()方法稍微修改,以保留原来的样式字符串/属性:
$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
#3
135
You can set the width directly using .width()
like this:
可以直接使用.width()设置宽度:
$("#elem").width(100);
Updated for comments: You have this option as well, but it'll replace all css on the element, so not sure it's any more viable:
更新的评论:您也有这个选项,但是它将替换元素上的所有css,所以不确定它是否更可行:
$('#elem').css('cssText', 'width: 100px !important');
#4
62
var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
#5
51
David Thomas’s answer describes a way to use $('#elem').attr('style', …)
, but warns that using it will delete previously-set styles in the style
attribute. Here is a way of using attr()
without that problem:
David Thomas的回答描述了使用$('#elem')的方法。attr('style',…),但是警告说使用它将会删除样式属性中预先设置的样式。这里有一个使用attr()的方法,没有这个问题:
var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
As a function:
作为一个函数:
function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');
Here is a JS Bin demo.
这是一个JS Bin演示。
#6
27
After reading other answers and experimenting, this is what works for me:
在阅读了其他答案和实验之后,这就是我的工作:
$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
This doesn't work in IE 8 and under, though.
但这在IE 8和under中都不起作用。
#7
22
You can do this:
你可以这样做:
$("#elem").css("cssText", "width: 100px !important;");
Using "cssText" as the property name and whatever you want added to the css as it's value.
使用“cssText”作为属性名称,以及您想要添加到css中的任何内容。
#8
15
You can achieve this in two ways:
你可以通过以下两种方式实现:
$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
#9
12
Kinda late but here is what I did after encountering this problem...
有点晚了,但这是我遇到这个问题后做的…
var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style',origStyleContent+';width:150px !important');
#10
12
There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.
没有必要去关注@AramKocharyan的答案的复杂性,也不需要动态地插入任何样式标签。
Just overwrite style, but you don't have to parse anything, why would you?
只是覆盖风格,但你不需要解析任何东西,为什么?
//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' : '') + ';');
}
Can't use removeProperty()
because it wont remove !important
rules in Chrome.
Can't use element.style[property] = ''
because it only accepts camelCase in FireFox.
不能使用removeProperty(),因为它不会删除!不能使用元素。style[属性]= "因为它只接受FireFox中的camelCase。
You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, IE8 etc
您可能会用jQuery来缩短这个时间,但是这个函数将会在现代浏览器上运行,IE8等等。
#11
9
If it is not so relevant and since you're dealing with one element which is #elem
, you can change its id to something else and style it as you wish...
如果它不那么相关,并且因为您正在处理一个元素,那就是#elem,您可以将它的id更改为其他的,并按照您的意愿来样式化它。
$('#elem').attr('id','cheaterId');
and in your css:
和你的css:
#cheaterId { width: 100px;}
hope this helps, Sinan.
希望这有助于,斯楠。
#12
9
The easiest and best solution for this problem from me was to simply use addClass() instead of .css() or .attr().
对于这个问题,最简单和最好的解决方案是简单地使用addClass()而不是.css()或.attr()。
For example:
例如:
$('#elem').addClass('importantClass');
$(' # elem ').addClass(“importantClass”);
And in your css file:
在你的css文件中:
.importantClass {
width: 100px !important;
}
#13
9
This solution doesn't override any of the previous styles, it just applies the one you need:
这个解决方案不会覆盖任何之前的样式,它只适用于您需要的一个样式:
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);
}
#14
8
Instead of using the css()
function try the addClass()
function:
不要使用css()函数尝试addClass()函数:
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>
#15
6
We need first remove previous style. I remove using a regular. I send you a example for change color,...
我们需要先去掉之前的样式。我用一个普通的。我给你举个颜色改变的例子……
var SetCssColorImportant = function (jDom, color) {
var style = jDom.attr('style');
style = style.replace(/color: .* !important;/g, '');
jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
#16
6
An alternative way to append style in head
另一种附加样式的方法。
$('head').append('<style> #elm{width:150px !important} </style>');
this appends style after all your css files so it will have higher priority than other css files and will be applied
这个附加样式在所有css文件之后,所以它将比其他css文件有更高的优先级,并将被应用。
#17
6
May be look's like this:
可能是这样的:
cache
缓存
var node = $('.selector')[0]; OR var node = document.querySelector('.selector');
set css
设置css
node.style.setProperty('width', '100px', 'important');
remove css
删除css
node.style.removeProperty('width'); OR node.style.width = '';
#18
6
FYI, it doesn't work because jQuery doesn't support it. There was a ticket filed on 2012 (#11173 $(elem).css("property", "value !important") fails) that was eventually closed as WONTFIX.
FYI,它不起作用,因为jQuery不支持它。有一张2012年的机票(elem)。css(“属性”、“值!重要”)失败了,最终以“WONTFIX”关闭。
#19
5
Why not just doing like this:
为什么不这样做:
$("#elem").get(0).style.width= "100px!important";
#20
4
I would assume you tried it without adding important?
inline css (which is how js adds styling) overrides stylesheet css. I'm pretty sure that's the case even when the stylesheet css rule has !important.
我认为你试过没有添加重要的东西?内联css (js添加样式)覆盖了样式表css。我很确定,即使样式表css规则有!
Another question (maybe a stupid question but must be asked.): is the element you are trying to work on, is it display:block; or display:inline-block; ?
另一个问题(可能是一个愚蠢的问题,但必须要问。):你正在努力工作的元素是:block;或显示:inline-block;吗?
not knowing your expertise in CSS.. inline elements don't always behave as you would expect.
不知道你在CSS方面的专长。内联元素并不总是像您期望的那样表现。
#21
3
It may or may not be appropriate for your situation but you can use CSS selectors for a lot of these type of situations.
它可能适合您的情况,也可能不适合您,但是您可以使用CSS选择器来处理许多此类情况。
If, for example you wanted of the 3rd and 6th instances of .cssText to have a different width you could write:
例如,如果您希望.cssText的第3和第6实例具有不同的宽度,您可以编写:
.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}
Or:
或者:
.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
#22
3
I think it work ok and can overwrite any other css before(this: DOM element):
我认为它可以工作,并且可以在之前覆盖任何其他css(这是DOM元素):
this.setAttribute('style', 'padding:2px !important');
#23
2
I also discovered that certain elements or add-on's (like Bootstrap) have some special class cases where they do not play well with !important
or other work-arounds like .addClass/.removeClass
, and thus you have to to toggle them on/off.
我还发现,某些元素或附加组件(如Bootstrap)有一些特殊的类情况,它们不能很好地发挥作用!重要的或其他的工作方式。removeClass,因此你必须切换它们。
For example, if you use something like <table class="table-hover">
the only way to successfully modify elements like colors of rows is to toggle the table-hover
class on/off, like this
例如,如果您使用像
$(your_element).closest("table").toggleClass("table-hover");
$(your_element).closest .toggleClass(“表”)(“table-hover”);
Hopefully this work-around will be helpful to someone! :)
希望这样的工作对某人有帮助!:)
#24
2
we can use setProperty or cssText to add !important to dom element using java script.
我们可以使用setProperty或cssText来添加!使用java脚本对dom元素非常重要。
Eg1:
烤箱
elem.style.setProperty ("color", "green", "important");
Eg2:
Eg2:
elem.style.cssText='color: red !important;'
#25
2
I had the same problem trying to change a text color of a menu-item when "event". The best way i found when i had this same problem is:
当“事件”时,我试图更改菜单项的文本颜色时遇到了同样的问题。当我遇到同样的问题时,我发现的最好的方法是:
1st step: Create, in your css, a new class with this purpose, for example:
第一步:在css中创建一个带有这个目的的新类:
.colorw{ color: white !important;}
last step: Apply this class using addClass method as follows:
最后一步:使用addClass方法应用这个类:
$('.menu-item>a').addClass('colorw');
Problem solved. Hope it helps!
问题解决了。希望它可以帮助!
#26
2
3 working examples
I had a similar situation, but I used .find() after struggling with .closest() for a long time with many variations.
我遇到过类似的情况,但我使用了。find()在与.最近的()进行了很长时间的变化。
The Example Code
// allows contains fuction 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 1000ms
});
Alternative
$( '.inner' ).each(function () {
this.style.setProperty( 'height', '50px', 'important' );
});
$('#out').find('.inner').css({ 'height': '50px'});
Up vote if you found any use, thanks.
如果你发现有用,请举手,谢谢。
Working: http://jsfiddle.net/fx4mbp6c/
工作:http://jsfiddle.net/fx4mbp6c/
#27
1
https://jsfiddle.net/xk6Ut/256/
https://jsfiddle.net/xk6Ut/256/
An alternative approach is dynamically creating and updating CSS class in JavaScript. To do that, we can use style element and need to employ the ID for the style element so that we can update the CSS class
另一种方法是动态地创建和更新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)
#28
1
The safest workaround to this is to add class then do the magic in CSS :-), addClass()
and removeClass()
should do the work.
最安全的方法是添加类,然后在CSS中执行魔法:-),addClass()和removeClass()应该完成工作。
#29
-6
Another easy method to solve this issue adding the style attribute:
另一个简单的方法来解决这个问题,添加样式属性:
$('.selector').attr('style', 'width:500px !important');