Search

1/12/2009

manipulate css by javascript

http://chunghe.googlecode.com/svn/trunk/experiment/manipulate.css.by.javascript/javascript.inline.important.htm


// inserting css styles to the existing css file
var ss = document.styleSheets[0];
var rules = ss.cssRules?ss.cssRules:ss.rules;

if(typeof ss.insertRule != 'undefined')
ss.insertRule("#foo{background:blue !important}", rules.length);
else if(typeof ss.addRule != 'undefined')
ss.addRule('#foo', 'background:blue !important', rules.length);

更簡單一點的方法是,新增一個 stylesheet 掛在 document.body 裡面

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '#foo{background: blue !important}';
document.body.appendChild(style);

不過上面的寫法在 IE 下會有 "未知的執行階段錯誤",正確的寫法如下:

var csstext = 'body{background:blue !important}';
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
if (style.styleSheet) { // for IE
style.styleSheet.cssText = csstext;
} else { // for everyone else
var textNode = document.createTextNode(csstext);
style.appendChild(textNode);
}
document.body.appendChild(style);

cross browser insertRule

var style = document.createElement("style");
document.getElementsByTagName("head")[0].appendChild(style);
var sheet = style.sheet||style.styleSheet;
var n = function(m, Y) {
var wrap = m + " { " + Y + " }";
sheet.insertRule ? sheet.insertRule(wrap, sheet.cssRules.length) : sheet.addRule(m, Y);
};
n('#foo', 'display: block !important');

沒有留言: