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(스타일객체)의 마지막 원소로 클래스가 추가된다.
반응형
'JavaScript > 사용자함수' 카테고리의 다른 글
[JavaScript][사용자함수] input 한글입력 막기 (0) | 2017.02.24 |
---|---|
[JavaScript][사용자함수] 브라우저 F11 전체화면 체크 (0) | 2017.02.13 |
[JavaScript][사용자함수] 숫자 세자리 마다 콤마 붙이기 (0) | 2016.10.13 |
[JavaScript][사용자함수] replaceAll - 검색된 모든 문자열 바꾸기 (0) | 2016.06.02 |
[JavaScript][사용자함수] input maxlength 속성 제어 함수 - 글자수 제한, 유효성검사 (0) | 2016.03.10 |