random background colour of a web page every refresh
To randomly generate a background color for a web page every time it is refreshed, you can use JavaScript. Here's an example:
- First, create a CSS class that sets the background color. For example:
body {
background-color: #FFFFFF; /* default background color */
}
- In the JavaScript code, create an array of possible background colors:
var colors = ['#FF5733', '#FFE633', '#33FF57', '#33BFFF', '#B533FF', '#FF33B3'];
- Generate a random number between 0 and the length of the colors array:
var randomColorIndex = Math.floor(Math.random() * colors.length);
- Use the random number to select a color from the array:
var randomColor = colors[randomColorIndex];
- Set the new background color using JavaScript:
document.body.style.backgroundColor = randomColor;
- Put all the code together in a function and call it when the page loads:
function changeBackgroundColor() {
var colors = ['#FF5733', '#FFE633', '#33FF57', '#33BFFF', '#B533FF', '#FF33B3'];
var randomColorIndex = Math.floor(Math.random() * colors.length);
var randomColor = colors[randomColorIndex];
document.body.style.backgroundColor = randomColor;
}
window.onload = changeBackgroundColor;
This will randomly generate a background color every time the page is refreshed or loaded.
原文地址: http://www.cveoy.top/t/topic/0ia 著作权归作者所有。请勿转载和采集!