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
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 Answer

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


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

...