问题
I want to have a javascript file which checks if current time is between 7pm and 7am. If so it should change the background color on my website to X. If the current time is not between 7pm and 7am the background color should be Y. Since I am new to Javascript I do not know everything, and that's why I need your help!
回答1:
var today = new Date().getHours();
if (today >= 7 && today <= 19) {
document.body.style.background = "Red";
} else {
document.body.style.background = "Blue";
}
See fiddle.
回答2:
I suggest using a class on the body to manage the style, but handle the classes in JavaScript.
Essentially you'll use the Date class to get the current hour in military time (24 hour). 7 PM is represented as 19 in military time.
var hour = new Date().getHours();
// between 7 PM and 7 AM respectively
if(hour >= 19 || hour <= 7) {
document.body.className += 'between7';
} else {
document.body.className += 'notBetween7';
}
Then in CSS you can handle those classes.
body.between7 {
background-color: green;
}
body.notBetween7 {
background-color: red;
}
回答3:
Here is JSBin
var currentTime = new Date().getHours();
if (currentTime >= 19 && currentTime <= 7) {
document.body.style.background = "/*your X color*/";
} else {
document.body.style.background = "/*your Y color*/";
}
回答4:
var d = new Date();
var n = d.getHours(); //get the current local time's hour in military time (1..23)
//If the time is greater than or equal to 7pm or less than or equal to 7am
if (n >= 19 || n <= 7) {
//set background color to X
}
else {
//set background color to Y
}
回答5:
This may be help you :
function checkTime() {
var d = new Date(); // current time
var hours = d.getHours();
var mins = d.getMinutes();
if(hours>=19 || hours <=7)
{
document.body.style.background="";//set background color x
}
else
{
document.body.style.background="";//set background color y
}
}
回答6:
You have to wrap it in DOMContentLoaded
event so it's fired before CSS and images etc...
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading
Ref : https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Event listener :
document.addEventListener("DOMContentLoaded", function(event) {
var currentHour = new Date().getHours();
var themeClassName = (currentHour >= 19 || currentHour <= 7) ? "night-class-name" : "day-class-name";
document.body.className += themeClassName
});
来源:https://stackoverflow.com/questions/18031410/javascript-if-time-is-between-7pm-and-7am-do-this