點擊按鈕,為指定 <div> 產生隨機十六進位顏色代碼(如 #3A7F2E)並套用為背景色。核心在於:隨機從 0-9A-F 字符集取 6 位字符,拼接成合法 CSS 顏色值。
<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312">
<title>JS 設置隨機顏色</title>
</head>
<body>
<div id="myDiv" style="width:200px;height:200px;"></div>
<input type="button" value="給 myDiv 設置隨機背景顏色" onclick="setColor()" />
<script>
// 產生隨機顏色代碼
function getcl() {
var arr = [], i = 0;
var C = '0123456789ABCDEF'; // 16 進位字符集
while (i++ < 6) {
var x = Math.random() * 16; // 0-16 隨機浮點
var b = parseInt(x); // 取整 0-15
var c = C.substr(b, 1); // 取對應字符
arr.push(c);
}
return "#" + arr.join(''); // 拼接為 #RRGGBB
}
// 套用到目標元素
function setColor() {
document.getElementById("myDiv").style.backgroundColor = getcl();
}
</script>
</body>
</html>
'0123456789ABCDEF' 涵蓋十六進位所有字符Math.random() * 16 產生 [0, 16),parseInt 取整得 0-15 索引join(''):無縫拼接,避免逗號干擾#:形成標準 CSS 顏色值// 箭頭函數 + 模板字串 + 位運算
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0').toUpperCase()}`;
// 或更簡潔(ES6)
const randomColor = () => `#${(Math.random() * 0xFFFFFF << 0).toString(16).padStart(6, '0')}`;
// 使用
document.getElementById('myDiv').style.backgroundColor = randomColor();
linear-gradient(45deg, #abc, #def)document.querySelectorAll() 為多元素分配不同隨機色隨機顏色生成是 JS 入門經典練習,涵蓋 Math.random、字符串操作、DOM 樣式修改。理解十六進位顏色結構與位運算優化,能寫出更簡潔、高效的代碼。