I am looking to write a script which:
How could I do this without loads of IF statements?
Looking here: https://stackoverflow.com/a/1455177/560287 it says there are 16776960 different colors, I dont need that many but how could I reduce this into a setInterval
so it fades through the colors of a rainbow every second?
Make an hourly colour array, one for each hour.
var hourly = "#ff00cc,red,green,blue...".split(",")
Then set the background to the element matching the current hour:
var d = new Date();
var h = d.getHours();
$('body').css('background-color',hourly[h])
Put this script at the top of your page and on reload it will set the colour.
This is not "constantly" changing, but it gives you a start point.
This works:
First lets make the function that will do it:
"use strict";
function changeColor() {
//rgb
console.log('event fired');
var colors = [0, 0, 0];
var hour = new Date().getHours();
console.log(hour);
//Will get an valid rgb color
var color = parseInt(255/24*hour);
console.log(color);
for(var i = 0; i < colors.length; i++) {
colors[i] = color;
}
//add the color to the element you want:
document.body.style.backgroundColor = "rgb("+colors[0] + "," + colors[1] + "," + colors[2] + ")";
console.log("event fired. color get:" + colors[0] + colors[1] + colors[2]);
}
After, let's make a event that will be fired in each 30 minutes(the color will be changed every 30 minutes):
setInterval(changeColor,1800000);
You could calculate the rgb/a difference between two colors and increase/decrease it by the current daytime. At the first, we need something that does the color parsing part for us.
var parseColor = function (start, end, now) {
return [
start[0] + now * (end[0] - start[0]) | 0,
start[1] + now * (end[1] - start[1]) | 0,
start[2] + now * (end[2] - start[2]) | 0,
(start[3] && end[3]) ? (start[3] + now * (end[3] - start[3]) | 0) : 1
];
};
Now, let's define a really simple wrapper around the date calculations and color parsing.
var daytimeColor = function (start, end, date) {
date = date || new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var now = hour * minute / 1440;
var rgba = parseColor(start, end, now);
return 'rgba(' + rgba.join() + ')';
};
Last but not least call it and pass your color arrays in:
var start = [255, 0, 0];
var end = [0, 0, 255];
document.body.style.backgroundColor = daytimeColor(start, end);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.