简体   繁体   English

使用 JS/JQuery 根据日期/时间更改图像

[英]Change image based on date/time with JS/JQuery

I am using the below code to switch between 2 class names on a page element based on what time of the day it is.我正在使用下面的代码根据一天中的时间在页面元素上的 2 个 class 名称之间切换。 Currently the class name will switch between the hours of 07:00AM - 23:00PM.目前 class 名称将在 07:00AM - 23:00PM 之间切换。

Is it possible to alter this code so that we could have one timeframe for days Monday - Friday and another timeframe for Saturday and Sunday?是否可以更改此代码,以便我们可以有一个周一至周五的时间范围和周六和周日的另一个时间范围?

jQuery(function ($) {
window.setInterval(SetImage,0);   /* set this to at least 10 min */

function SetImage(){
    var nowdate = new Date();
    var waketime = new Date();
    waketime.setHours(7);
    waketime.setMinutes(00);

    var bedtime = new Date();
    bedtime.setHours(23);
    bedtime.setMinutes(00);

    if(waketime < nowdate  && nowdate < bedtime) {
         document.body.setAttribute('data-daytime','');
    }else{
         document.body.setAttribute('data-nighttime','');
    }
}
});

Yes, you can take a look at getDay() to get what day it is.是的,您可以查看getDay()以了解今天是哪一天。

you can do something like this你可以做这样的事情

const defaultSchedule = { wake: 7, bed: 23 }
const schedule = {
  // Sunday - Saturday : 0 - 6
  0: { wake: 9, bed: 23 },
  6: { wake: 9, bed: 03 },
}
const times = schedule[new Date().getDay()] || defaultSchedule
waketime.setHours(times.wake);
bedtime.setHours(times.bed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM