我很难应用这样的风格!重要的我尝试过:
$("#elem").css("width", "100px !important");
这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?
编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。
此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。
我很难应用这样的风格!重要的我尝试过:
$("#elem").css("width", "100px !important");
这没有任何作用;不应用任何宽度样式。有没有类似jQuery的方法来应用这样的样式而不必覆盖cssText(这意味着我需要先解析它,等等)?
编辑:我应该补充一下,我有一个带有!我试图用!重要的样式内联,因此使用.width()等不会起作用,因为它会被我的外部重写!重要的风格。
此外,将覆盖上一个值的值是计算出来的,因此我不能简单地创建另一个外部样式。
当前回答
最安全的解决方法是添加一个类,然后在CSS中执行魔术:-),addClass()和removeClass()应该完成这项工作。
其他回答
您可以通过两种方式实现这一点:
$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
它可能适合也可能不适合您的情况,但您可以在许多此类情况下使用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;}
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,并将重要标记添加到元素中:可以这样做(例如,如果需要设置重要标记的宽度)
$('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
不要使用css()函数,请尝试addClass()函数:
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>