JavaScript 生成随机十六进制颜色的代码
要使用 JavaScript 生成随机十六进制颜色代码,代码如下 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { box-sizing: border-box; font-size: 18px; font-weight: 500; color: white; width: 150px; height: 150px; text-align: center; padding-top: 4%; } </style> </head> <body> <h1>Generate random hex codes of color</h1> <button class="Btn">GENERATE</button> <div class="result"></div> <h3> Click on the above button to generate a random hex color code </h3> <script> let resultEle = document.querySelector(".result"); let hexCode = "0123456789ABCDEF"; let Color = "#"; document.querySelector(".Btn").addEventListener("click", () => { for (let i = 0; i < 6; i++) Color += hexCode[Math.floor(Math.random() * 16)]; resultEle.style.backgroundColor = Color; resultEle.innerHTML = Color; }); </script> </body> </html>
输出
在单击“生成”按钮时 −
广告