2007-11-17

CSS/DOM : 動的にスタイルシートへルールを追加する

スタイル属性を動的に一括して設定します。
引数にはセレクタとルールを指定します。

//使用例
//addCSSRule(selector, declaration);

addCSSRule('div.test', 'width:200px; height:100px;');
addCSSRule('div.test', 'background:#ccc;');

var addCSSRule = (/*@cc_on!@*/false)
    ? (function(sheet){
          return function(selector, declaration){
              sheet.addRule(selector, declaration);
          };
      })(document.createStyleSheet())
    : (function(sheet){
          return function(selector, declaration){
              sheet.insertRule(selector + '{' + declaration + '}', sheet.cssRules.length);
          };
      })((function(e){
            e.appendChild(document.createTextNode(''));
            (document.getElementsByTagName('head')[0] || (function(h){
                document.documentElement.insertBefore(h, this.firstChild);
                return h;
            })(document.createElement('head'))).appendChild(e);
            return e.sheet;
        })(document.createElement('style')))
    ;


資料

0 件のコメント: