简体   繁体   English

如何忽略CSS类的宽度并通过代码将其设置为!important

[英]How to ignore css class's width and set it by code as !important

I have a div with width as 50% added as a class, 我有一个div,宽度为班级的50%,

In document ready I am doing this, 在准备文档时,我正在这样做,

$("#id").width('100%');

But the rule is being ignored. 但是规则被忽略了。

How can i make my code one must use? 我该如何使我的代码必须使用?

Try using jQuery's .css() function ( JSFiddle example ): 尝试使用jQuery的.css()函数( JSFiddle示例 ):

$("#id").css("width", "100%");

If you really want to set it as !important : 如果您真的想将其设置为!important

$("#id").css("width", "100% !important");

esqew is correct, but this is usually a "bad" way to fix things. esqew是正确的,但这通常是解决问题的“坏方法”。 "usually", you're better off using css inheritance and avoiding "!important" statements ( let alone dynamic !important statements). 通常,最好使用CSS继承并避免使用“!important”语句(更不用说动态!important语句了)。

See How to access an element within an element in css? 请参见如何访问CSS元素中的元素? for some info on someone trying to achieve a similar thing. 有关尝试实现类似目标的某人的一些信息。

Expanding on esqew's fiddle, you could do this: http://jsfiddle.net/rHYc4/2/ 扩展esqew的提琴,您可以这样做: http : //jsfiddle.net/rHYc4/2/

#outer-div #id { width: 100%; }
  1. If the CSS you are trying to change already has "!important" on it, you will need to use !important to override it. 如果您要更改的CSS上面已经带有“!important”,则需要使用!important来覆盖它。
  2. If the CSS you are trying to override does not have !important, you should use a more specific selector to change it. 如果您要覆盖的CSS没有!important,则应使用更具体的选择器进行更改。
  3. If it still doesn't change after both approaches, you can just remove the width $('#id').css("width",""); 如果两种方法仍然没有改变,则可以删除宽度$('#id').css("width",""); and then do whatever you like! 然后做你喜欢的事!

post-comment edit 评论后

if you are seeing something like <div id='id' width='100%'>blah blah</div> you would use jQuery's attr to get rid of it: $('#id').removeAttr('width',''); 如果看到类似<div id='id' width='100%'>blah blah</div>东西,则可以使用jQuery的attr摆脱它: $('#id').removeAttr('width',''); to kill it or $('#id').attr('width','100%'); 杀死它或$('#id').attr('width','100%'); to set it. 设置它。

See http://api.jquery.com/attr/ and http://api.jquery.com/removeattr/ 参见http://api.jquery.com/attr/http://api.jquery.com/removeattr/

Since you mentioned you're setting the width with a class, keep it in the CSS and avoid manipulating the width in the JS. 既然您提到过要使用类设置宽度,请将其保留在CSS中,并避免在JS中操纵宽度。 Instead, use another class, like such: 而是使用另一个类,例如:

#id {width: 50%}
#id.new-class {width: 100%}

Then in document ready 然后准备好文件

$("#id").addClass("new-class");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM