英文:
Can anyone tell how to generate random colors for the background for websites using css?Is it possible?
问题
我们可以使用Unsplash图像源来随机显示图像。同样,我们可以使用纯CSS来实现背景颜色的随机吗?
如果可以的话,有人可以告诉我如何实现吗?
我尝试使用随机函数来生成背景颜色,但没有产生任何输出。
英文:
like we can use random images using unsplash image source. Similarly can we do it for background colors using css only??
If yes can anyone tell how to do it?
well i used random function to generate random colors for the background in styling. But it didnt give any output
答案1
得分: 1
以下是您要翻译的内容:
这将需要至少一些JS来随机生成颜色
const container = document.getElementById('element');
generateRandomColor();
function generateRandomColor() {
// 16777215是十六进制FFFFFF的十进制等值
const randomHex = Math.floor(Math.random() * 16777215).toString(16);
container.style.backgroundColor = `#${randomHex}`;
container.innerHTML = `#${randomHex}`;
}
.container {
height: 100px;
width: 100%;
border: 1px solid black;
margin-bottom: 5px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 24px;
}
<div id="element" class="container"></div>
<button onclick="generateRandomColor()">Generate Random Color</button>
英文:
This would require at least some JS to generate colors at random
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const container = document.getElementById('element');
generateRandomColor();
function generateRandomColor() {
// 16777215 is decimal equivalent of FFFFFF in hexadecimal
const randomHex = Math.floor(Math.random() * 16777215).toString(16);
container.style.backgroundColor = `#${randomHex}`;
container.innerHTML = `#${randomHex}`;
}
<!-- language: lang-css -->
.container {
height: 100px;
width: 100%;
border: 1px solid black;
margin-bottom: 5px;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
font-size: 24px;
}
<!-- language: lang-html -->
<div id="element" class="container"></div>
<button onclick="generateRandomColor()">Generate Random Color</button>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论