我很难应用这样的风格!重要的我尝试过:
$("#elem").css("width", "100px !important");
这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?
编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。
此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。
我很难应用这样的风格!重要的我尝试过:
$("#elem").css("width", "100px !important");
这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?
编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。
此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。
当前回答
它可能适合也可能不适合您的情况,但您可以在许多此类情况下使用CSS选择器。
例如,如果您希望.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;}
其他回答
我认为它工作正常,可以覆盖之前的任何其他CSS(this:DOM元素):
this.setAttribute('style', 'padding:2px !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
可能是这样的:
隐藏物
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 = '';
David Thomas的回答描述了一种使用$(“#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演示。
可以直接使用.width()设置宽度,如下所示:
$("#elem").width(100);
更新征求意见:您也有这个选项,但它将替换元素上的所有css,因此不确定它是否更可行:
$('#elem').css('cssText', 'width: 100px !important');