我一直在尝试修改我的网站http://www.gfcf14greendream.com/,方法是使用 javascript 根据季节更改背景(并消除字体颜色的阅读问题,只要背景发生变化作品),围绕一个简单的功能工作:
function setSeasonTheme() {
var today = new Date();
var first = new Date(today.getFullYear(), 0, 1);
var dayYear = Math.round(((today - first) / 1000 / 60 / 60 / 24) + .5, 0);
if (dayYear >= 1 && dayYear < 80)
{
document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/winterbg.png");
}
if (dayYear >= 80 && dayYear < 172)
{
document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/springbg.png");
}
if (dayYear >= 172 && dayYear < 264)
{
document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/summerbg.png");
}
if (dayYear >= 264 && dayYear < 355)
{
document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/fallbg.png");
}
if (dayYear >= 355 && dayYear <= 366)
{
document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/winterbg.png");
}
}
这应该根据它所在的年份更改页面的背景,修改此 div 上的 img 标签:
<div id="background">
<img id="mainbg" src="https://i.stack.imgur.com/USDq5.png" class="stretch" alt="" />
</div>
但是,图像的原始 URL http://www.gfcf14greendream.com/images/greentwi.png仍然出现。而通过函数,它的 src 应该是http://www.gfcf14greendream.com/images/summerbg.png。当调试器到达这一行时document.getElementById("mainbg").setAttribute('src', "http://www.gfcf14greendream.com/images/summerbg.png");
,我得到了这个错误:
Uncaught TypeError: Cannot call method 'setAttribute' of null
为什么会这样?如果显示原始图像,为什么背景的img标签应该为null?感谢任何可以为我提供帮助或建议的人。