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
2.0k views
in Technique[技术] by (71.8m points)

can jquery manipulate the global css definition of the document?

i'm trying to make a checkbox that will hide a specific css class when clicked, but i also want this effect to apply to all future objects that get that specific class.

for example: i have 2 divs:

divA is of class abc

divB has no class

i want the checkbox to hide all divs of class abc, this is easy, using $(".abc").hide(). but the problem is that if another part of the site made divB of class abc later on, then it won't be hidden. because the jquery code would've only applied to divA at the time.

what i'm trying to do is make the checkbox manipulate the global css definition of the document. so when the user clicks the checkbox, i would change the abc class to be hidden, and later whenever any div joins that class, it would be hidden.

is this possible in jquery?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use the insertRule and addRule (when necessary) methods to add new rules to the .abc selector. That should affect anything in the future that gets that class applied to it.

var stylesheet = document.styleSheets[0],
    selector = ".abc", rule = "{color: red}";

if (stylesheet.insertRule) {
    stylesheet.insertRule(selector + rule, stylesheet.cssRules.length);
} else if (stylesheet.addRule) {
    stylesheet.addRule(selector, rule, -1);
}

There is a jQuery plugin for this also: $.rule(); It's available at https://github.com/flesler/jquery.rule


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

...