【问题标题】:change image according to world time zones?根据世界时区更改图像?
【发布时间】:2015-08-06 10:39:57
【问题描述】:

我想在 html 中制作一个横幅,其中图像根据一天的时间而变化,即我想在晚上 7 点到早上 6 点之间显示一个图像,而在其他时间显示另一个图像。在搜索了 wen 之后,我发现了一个 website,它做同样的事情。在此图像根据系统时间更改,但我想根据世界时区更改图片。例如。我希望图像根据日本的时区而改变。 这是JS代码:

function pixTimeChange() {
  var t=new Date();
  var h = t.getHours();
  var r1="obanner1.jpg";
  var r2="poolside3.png";
  var el=document.getElementById('myimage');

  // See the time below. Note: The time is in 24 hour format.
  // In the example here, "7" = 7 AM; "17" =5PM.
  el.src = (h>=7 && h<16) ? r1 : r2;
}

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  pixTimeChange();
});

我对 Javascript 和 jQuery 的了解有限,需要帮助来更改此脚本。 抱歉,如果这个问题超出了 SO 的范围。

【问题讨论】:

  • 你能提供一个小提琴吗?顺便说一句,您的 pixTimeChange 函数可以正常工作。
  • 这段代码有效,对吧?你只需要条件来检查时区?
  • 对,代码工作得很好,但我需要时区条件?
  • Javascripts 日期对象为您提供“客户”时区的日期。
  • 你能详细说明一下吗?

标签: javascript


【解决方案1】:

查看this question 以获取时区。

然后你可以使用 JQuery 为你的图片设置 src 参数,像这样:

if (userIsInJapan) {
  $("#YourImgID").attr("src", r1);
}else{
  $("#YourImgID").attr("src", r2);
}

编辑:

我在this thread中找到了有关如何检查时区的更多详细信息

我制作了this little example来告诉你如何使用它

<script>

function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() - (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for "+ city +" is "+ nd.toLocaleString();
}
// Refresh the timer every 250 milliseconds
setInterval(function(){
    $("#timeLabel").text(calcTime('Japan', '+6'));
}, 250)
</script>
<label id="timeLabel"></label>

【讨论】:

  • userIsInJapan 到底是什么值?
  • 我这样做是为了说明,这将是一个布尔条件(真或假)。
猜你喜欢
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2017-04-06
相关资源
最近更新 更多