我想定位这个:
<h3 id='month'>Oct</h3>
我这样做了:
var changeColor = function () {
var monName = new Array ('Jan' ... 'Dec'); //ellipsis to make code short
var now = new Date();
if(monName == monName[now.getMonth()]) {
switch(monName) {
case 'Jan':
document.getElementById('month').style.backgroundColor = '#ff3300';
break;
.
.
.
.
case 'Dec':
document.getElementById('month').style.backgroundColor = '#c2dd8a';
break;
default:
alert('Error');
}
}
};
我在 html body 元素中调用了该函数(脚本标记之间的外部 js 文件已经正确获取来源):
<script type='text/javascript' src='time.js'></script>
<body onload='changeColor();'>
好像没用。我怀疑我定位 h3 元素的方式存在错误。我的总体想法是随着目标元素的月份变化而改变背景颜色。任何帮助是极大的赞赏。谢谢!
最佳答案
尝试将您的 if
语句更改为:
if(document.getElementById('month').innerHTML == monName[now.getMonth()])
此外,您的 switch
语句应该是:
switch(monName[now.getMonth()])
关于javascript - 改变背景颜色 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13163702/