工作代码...它在每个页面加载时随机设置背景颜色...
function setCSS(selector, attribute, value) {
var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
found = false;
for (var S = 0; S < document.styleSheets.length; S++){
if(document.styleSheets[S][cssRuleCode]){
for(var n = 0; n < document.styleSheets[S][cssRuleCode].length; n++) {
if(document.styleSheets[S][cssRuleCode][n]["selectorText"] == selector) {
if(document.styleSheets[S][cssRuleCode][n].style[attribute]) {
document.styleSheets[S][cssRuleCode][n].style[attribute] = value;
found = true;
break;
}
}
}
}
}
if(!found) {
// Let's add
for (var S = 0; S < document.styleSheets.length; S++){
try {
document.styleSheets[S].insertRule(selector + ' { ' + attribute + ': ' + value + '; }',document.styleSheets[S][cssRules].length);
break;
} catch(err){
try {
document.styleSheets[S].addRule(selector, attribute + ': ' + value + ';');
break;
} catch (err){}
}
}
}
}
window.onload = function(){
urls = ["url('http://www.iwdownload.com/image/1982.png'), auto !important;",
"url('http://www.iwdownload.com/image/13534.gif'), auto !important;"];
var rand = Math.floor((Math.random() * urls.length));
setCSS("html, body, a, a:hover", "cursor", urls[rand]);
};
参考:使用 Javascript 更改 CSS 值
更新
要将背景颜色设置body
为蓝色,请使用
setCSS("body", "background", "blue");
**更新 2:博客 **
对于博主,将以下内容复制粘贴到</head>
博主模板 HTML 中。然后重新加载您的博客,背景应更改为随机颜色。
<script type="text/javascript">
function setCSS(selector, attribute, value) {
var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
for (var S = 0; S < document.styleSheets.length; S++){
if(document.styleSheets[S][cssRuleCode]){
for(var n = 0; n < document.styleSheets[S][cssRuleCode].length; n++) {
if(document.styleSheets[S][cssRuleCode][n]["selectorText"].indexOf(selector) != -1) {
if(document.styleSheets[S][cssRuleCode][n].style[attribute]) {
document.styleSheets[S][cssRuleCode][n].style[attribute] = value;
break;
}
}
}
}
}
}
window.onload = function(){
colors = ["red", "green", "blue", "yellow", "orange", "white"];
var rand = Math.floor((Math.random() * colors.length));
setCSS("body", "background", colors[rand]);
};
</script>