如何在网页上使用CSS生成随机背景颜色?这是否可行?

huangapple go评论57阅读模式
英文:

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(&#39;element&#39;);

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 -->

&lt;div id=&quot;element&quot; class=&quot;container&quot;&gt;&lt;/div&gt;
&lt;button onclick=&quot;generateRandomColor()&quot;&gt;Generate Random Color&lt;/button&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月29日 14:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578701.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定