1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function changeCSS(theClass, element, value) {
   //Last Updated on July 4, 2011
   //documentation for this script at
   //http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
   var cssRules;
 
   for (var S = 0; S < document.styleSheets.length; S++) {
 
      try {
 
         document.styleSheets[S].insertRule(theClass ' { ' + element ': ' + value '; }', document.styleSheets[S][cssRules].length);
 
      } catch (err) {
 
         try {
            document.styleSheets[S].addRule(theClass, element ': ' + value ';');
 
         } catch (err) {
 
            try {
               if (document.styleSheets[S]['rules']) {
                  cssRules 'rules';
               } else if (document.styleSheets[S]['cssRules']) {
                  cssRules 'cssRules';
               } else {
                  //no rules found... browser unknown
               }
 
               for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
                  if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
                     if (document.styleSheets[S][cssRules][R].style[element]) {
                        document.styleSheets[S][cssRules][R].style[element] = value;
                        break;
                     }
                  }
               }
            } catch (err) {
            }
         }
 
      }
      
   }
}
 
//changeCSS('클래스명', '속성명', '속성값');
changeCSS(".test""font-size""20px");
changeCSS(".test""background""pink");
 
var styleSheet = document.styleSheets[0];
var cssRules = styleSheet.cssRules 
console.log(cssRules);



changeCSS함수를 호출 할때마다 styleSheets(스타일객체)의 마지막 원소로 클래스가 추가된다.



반응형
Posted by 힘없는염소