使用javascript自动按月更改图片

时间:2014-11-27 17:28:44

标签: javascript php html css

我不知道这是否是提出问题的正确位置。

我想使用一个自动更改我网站起始网站图片的脚本。因此脚本应检查月份,如果月份是3月,则使用picture1.jpg,如果月份是8月,则使用picture2.jpg。

是否可以这样做,例如使用javascript?

我期待你的回答,如果你能帮我创建这样一个剧本,我会很高兴。

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个示例,可以修改代码:

<img id="Logo" src="Images/default.png" alt="KnowledgeBase" width="75%" onload="logo(this)" />


    function logo(img) {
      if (img.src.indexOf('default')==-1) return; // already changed 
      var d = new Date();
      var Today = d.getDate();
      var Month = d.getMonth();
      var src;
      if (Month === 10 && (Today >= 23 && Today <= 26)) {
        src = "Images/doodles/blah1.png";
      } else if (Month === 11 && (Today >= 23 && Today <= 26)) {
        src = "Images/doodles/blah2.png";
      } else if ((Month === 11 && Today >= 30) || (Month === 0 && Today <= 2)) {
        src = "Images/doodles/blah3.png";
      } else if (Month === 6 && (Today >= 3 && Today <= 5)) {
        src = "Images/doodles/blah4.png";
      } 
      img.src=src;
    }

DEMO

替代:

<script language="javascript" type="text/javascript"> 
var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); 
var thetime = new Date(); 
var themonth = thetime.getMonth(); 
document.write('<img src="image' + months[themonth] + '.gif" alt="Image of the month: ' + months[themonth] + '" />'); 
</script>

备选方案3:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="banner-container" style="width:400px;height:300px;"></div>

<script>
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var total = month;

// Summer
if (total >= 6 && total <= 8)
{
    document.getElementById("banner-container").style.backgroundImage = "url('images/winter.png')";
}
// Autumn
else if (total >= 9 && total <= 11)
{
    document.getElementById("banner-container").style.backgroundImage="url('images/fall.png')";
}
// Winter
else if (total == 12 || total == 1 || total == 2)
{
    document.getElementById("banner-container").style.backgroundImage = "url('images/winter.png')";
}
// Spring
else if (total >= 2 && total <= 6)
{
    document.getElementById("banner-container").style.backgroundImage = "url('images/spring.png')";
}
else
{
    document.getElementById("banner-container").style.backgroundImage = "url('images/summer.png')";
}
</script>

</body> </html>

更多信息:Changing image source based on date