就像我們可以使用 unsplash 圖像來(lái)源來(lái)使用隨機(jī)圖像一樣。同樣,我們可以只使用 css 來(lái)實(shí)現(xiàn)背景顏色嗎? 如果是的話誰(shuí)能告訴怎麼做?
我使用隨機(jī)函數(shù)為樣式中的背景產(chǎn)生隨機(jī)顏色。但它沒(méi)有給出任何輸出
這至少需要一些 JS 來(lái)隨機(jī)產(chǎn)生顏色
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}`; }
.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>