如何在一天中没有页面刷新的情况下更改背景图像 [英] How To Change Background Image by Time of Day Without Page-Refresh

查看:85
本文介绍了如何在一天中没有页面刷新的情况下更改背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的是根据一天中的小时更改页面的背景图像.这相当容易,因为它只需要通过Date对象检索小时,并检查其值即可.

What I'm looking to achieve is having the background image of my page change based on the hour of the day. This is fairly easy, as it only requires retrieving the hour through the Date object, and checking it's value.

var hour = new Date().getHours();
if (hour < 9 || hour > 18) {
    //set image through url
} else {
    //set another image through url
}

我实际上正在寻找的是动态更改背景图像(不刷新页面).我想出了一种使用上述逻辑来实现此目的的方法,但是我相信它会在每个经过的时间间隔内加载图像:

What I'm actually looking for is to have the background image change dynamically (no page refresh). I have come up with a method that does this with the above logic, but I believe it loads the image with every passing interval:

setInterval(function () {
     var hours = new Date().getHours();
     $("#hours").html((hours < 10 ? "0" : "") + hours);

     if (hours > 9 && hours < 18) {
          $("body").css("background-image", "url(../images/night-sky-background.jpg)");
     } else {
          $("body").css("background-image", "url(../images/day-sky-background.jpg)");
     }
}, 1000);

上面的代码将hours值写入页面,并将每隔一段时间检查一次它的值.它还每秒检查一次hours的值,并将相应地设置背景图像.恐怕这实际上不是解决此问题的好方法.原因如下:

The above code writes the hours value to the page and will check it's value every second with the interval. It also checks the value of hours every second and will set the background image accordingly. I'm afraid this is actually not a good way to approach this. Here's why:

秒间隔的小数位

我感觉实际上是每秒设置背景图像,这会导致糟糕的性能.

I have a feeling it is actually setting the background image every second which would result in terrible performance.

还有另一种方法可以解决这个问题吗?

Is there another way to approach this?

推荐答案

仅在更新前检查当前背景URL?

Just check the current background URL before updating it?

setInterval(function () {
     var hours = new Date().getHours();
     $("#hours").html((hours < 10 ? "0" : "") + hours);

     if (hours > 9 && hours < 18) {
          if($("body").css("background-image").indexOf("night-sky-background.jpg")==-1){
              $("body").css("background-image", "url(../images/night-sky-background.jpg)");
          }
     } else {
          if($("body").css("background-image").indexOf("day-sky-background.jpg")==-1){
             $("body").css("background-image", "url(../images/day-sky-background.jpg)");
          }
     }
}, 1000);

这篇关于如何在一天中没有页面刷新的情况下更改背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆