代码基于巴塞罗那市时区

时间:2015-07-29 13:34:04

标签: javascript jquery html

我有一个代码试图让巴塞罗那城市时间向我展示一个特定的背景和图像(基于一天中的小时),但似乎是不起作用。

JAVASCRIPT CODE

var now = new Date();
var offset = now.getTimezoneOffset();
var barcelona = new Date(now + (offset + 2*60)*60*1000);
var n = barcelona.getHours();

//1-2am if (n > 23 || n < 2) {
document.write('<body bgcolor="#2e3348" text="#FFFFFF">');
$("img#photo1").attr("src","images/head5.png");
}

//2-3am if (n > 24 || n < 4) {
document.write('<body bgcolor="#2e3348" text="#FFFFFF">');
$("img#photo1").attr("src","images/head4.png");
}

// and so go on - all the hours

这是我的HTML代码

<div class="Center-child-div">
    <div class="child-div">
        <img src="" id="photo1" />
    </div>
</div>

为什么不改变背景的任何解释都没有显示相应的.png图像?可能的方案?感谢

2 个答案:

答案 0 :(得分:2)

尝试使用&&运算符代替||。还要更加关注if条件:

var now = new Date(),
    offset = now.getTimezoneOffset(),
    barcelona = new Date(now + (offset + 2*60)*60*1000),
    n = barcelona.getHours();

// 1-2am 
if (n > 24 && n < 3) {
      $('body').css({
          'background-color': '#2e3348',
          'color': '#fff'
      });
      $("img#photo1").attr("src","images/head5.png");
} else
// 2-3am 
if (n > 1 && n < 4) {
      $('body').css({
          'background-color': '#2e3348',
          'color': '#fff'
      });
    $("img#photo1").attr("src","images/head4.png");
} else
// ......... if

答案 1 :(得分:0)

我运行了你的代码。问题是你有太多关闭括号。下次,您可以打开控制台日志,它将为您提供正在发生的任何Javascript错误。如果Javscript遇到错误,它将在该点停止运行,并且该点之后的任何代码都不会运行。

这是我使用过的代码并让它运行。

var now = new Date();
var offset = now.getTimezoneOffset();
var barcelona = new Date(now + (offset + 2*60)*60*1000);
var n = barcelona.getHours();

//1-2am if (n > 23 || n < 2) {
document.write('<body bgcolor="#2e3348" text="#FFFFFF">');
$("img#photo1").attr("src","images/head5.png");


//2-3am if (n > 24 || n < 4) {
document.write('<body bgcolor="#2e3348" text="#FFFFFF">');
$("img#photo1").attr("src","images/head4.png");

此外,我不确定您是否在某处包含jQuery,但如果没有它,则无法使用$引用。

相关问题