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

html - Change the style of an entire CSS class using javascript

Is there a way to change an attribute of a CSS class using javascript?

<style type="text/css">
  .fool select {
    display: block;
  }
</style>

<p class="fool">
  <select id="a" onchange="changeCSS()"> ... </select>
  <select id="b" > ... </select>
  <select id="c" > ... </select>
</p>

I want to change display:block to display:none for ALL <select> elements after a user call function changeCSS().

It looks simple but I can't find a way to do this...

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 modify style rules, but it's usually not the best design decision.

To access the style rules defined by style sheets, you access the document.styleSheets collection. Each entry in that collection will have a property either called cssRules or rules depending on the browser. Each of those will be a CSSRule instance. You can change the rule by changing its cssText property.

But again, that's probably not the best way to solve the problem. But it is the literal answer to your question.

The best way to solve the problem is probably to have another class in your stylesheet that overrides the settings of the previous rule, and then to add that class either to the select elements or to the container of them. So for instance, you could have the rules:

.fool select {
    display: block;
}
.fool.bar select {
    display: none;
}

...and when you want to hide the selects, add the "bar" class to the container that has the "fool" class.

Alternately, apply CSS style information directly to elements.


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

...