สร้างสีสุ่ม Hex Code (#RRGGBB) ด้วย Math.random() และ String Template
ตัวอย่าง (Vanilla JS)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Color</title>
<style>
#colorBox { width: 100px; height: 100px; border: 1px solid #ccc; }
</style>
</head>
<body>
<div id="colorBox" style="background-color: #FF0"></div>
<br><button onclick="pickRandomColor()">Random Color</button>
<script>
function getRandomColor() {
const hex = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += hex[Math.floor(Math.random() * 16)];
}
return color;
}
function pickRandomColor() {
document.getElementById("colorBox").style.backgroundColor = getRandomColor();
}
</script>
</body>
</html>
คำอธิบาย
- Hex Color: # + 6 ตัวอักษร (0-9, A-F)
Math.random() * 16→ 0-15.999 →Math.floor→ 0-15- ES6 Short Version:
('#' + Math.random().toString(16).slice(2, 8)).padEnd(7, '0') - หรือ:
`#${Math.floor(Math.random()*0xffffff).toString(16).padStart(6,'0')}`
ผลลัพธ์
เริ่มต้นสีเหลือง (#FF0) กดปุ่ม → สีสุ่มทุกครั้ง (เช่น #A3F2B1, #FF5733, #334455)