Home  >  Article  >  Web Front-end  >  js operation css implementation code_javascript skills

js operation css implementation code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:51:331171browse

When what we need is a rule, we cannot perform this operation every time the DOM changes, otherwise it will be too inefficient.
Fortunately, the css rules in the dom can also be modified. However, different browsers have different interface descriptions for CSS rules. IE uses a hash table-like method, while FF uses an array.
In terms of programmability, the interface description of ie is more popular with programmers, but logically, ff is obviously more reasonable.
I provide a simple packaging of the two sets of codes in a way similar to IE, but IE cannot be sure to honor the rules synchronously after the css removeRule of the dom. So it's better to use rule override instead of remove.
It should be noted that when using the js function, there must be at least one style tag on the page. Below is the code and examples.

Copy code The code is as follows:



<script> <br>function addCSSRule(key,value){ <br>var css = document.styleSheets[document.styleSheets.length-1]; <br>css.cssRules ? <br>(css.insertRule(key "{" value "}", css.cssRules.length)) : <br>(css.addRule(key,value)) ; <br>} <br>function removeCSSRule( key){ <br>for(var i = 0; i < document.styleSheets.length; i ){ <BR>var css = document.styleSheets[i]; <BR>css.cssRules ? <BR>(function (){ <BR>for(var j = 0; j < css.cssRules.length; j ){ <BR>if(css.cssRules[j].selectorText==key){ <BR>css.deleteRule( j); <BR>} <BR>} <BR>})() : <BR>(css.removeRule(key)) ; <BR>} <BR>} <BR></script>

abc



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn