Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - 如何使用.css()应用!important?(How to apply !important using .css()?)

I am having trouble applying a style that is !important .(我在应用!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.(编辑 :我应该补充一点,我有一个样式表,具有!important样式,我试图用!important样式内联重写,所以使用.width()之类的方法不起作用,因为它被我的外部!important样式覆盖。) Also, the value that will override the previous value is computed , so I cannot simply create another external style.(此外,将覆盖以前的值的值的计算 ,所以我不能简单地创建另一个外部风格。)   ask by mkoryak translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule.(问题是由jQuery无法理解!important属性引起的,因此无法应用该规则。)

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, and modified as suggested by falko in a comment:(上面的attr()方法略作修改以保留原始style字符串/属性,并按照falko在评论中的建议进行了修改:) $('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...