Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - How to add !important to a stylesheet rule using JavaScript?

I've got a reference to a CSSStyleRule object in JavaScript and I want to update the style for border-top-color to red !important. If I assign the value red, no problems occur. If I assign the value red !important, the value is ignored (i.e. not assigned).

myStyleSheetRule.style.borderTopColor = 'red'; // success
myStyleSheetRule.style.borderTopColor = 'red !important'; // fail

How do I set the !important flag?

Note that it has to be done via a stylesheet rule accessed programatically. In my use case, I can't assign a style attribute or anything else. I'm using Chrome on Windows 7.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Something like this should work:

HTML

<div id="colored">?</div>?????????????????????????

Default stylesheet

#colored {
    border-top: 1px solid Black;
}?

Javascript

var all = document.styleSheets,
    s = all[all.length - 1],
    l = s.cssRules.length;

if (s.insertRule) {
    s.insertRule('#colored {border-top-color: Red !important}', l);
} else {
    //IE
    s.addRule('#colored', 'border-top-color: Red !important', -1);
}?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...