JavaScript随机生成十六进制颜色

r囧r小猫 2023-10-06 22:00 177阅读 0赞

在这里插入图片描述

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>wgchen</title>
  6. <link rel="shortcut icon" href="#" />
  7. <meta name="keywords" content="https://wgchen.blog.csdn.net">
  8. <meta name="keywords" content="技术文章">
  9. <meta name="keywords" content="博客">
  10. <meta name="keywords" content="willem">
  11. <meta name="keywords" content="ycc">
  12. </head>
  13. <body>
  14. <p id="Id1">It is test 1.</p>
  15. <button type="button" onclick ="changeColor()">
  16. Change color
  17. </button>
  18. <script>
  19. function randomHexColor() {
  20. //随机生成十六进制颜色
  21. var hex = Math.floor(Math.random() * 16777216).toString(16);
  22. //生成ffffff以内16进制数
  23. while (hex.length < 6) {
  24. //while循环判断hex位数,少于6位前面加0凑够6位
  25. hex = '0' + hex;
  26. }
  27. return '#' + hex; //返回‘#'开头16进制颜色
  28. }
  29. function changeColor(){
  30. x=document.getElementById("Id1");
  31. x.style.color=randomHexColor();
  32. }
  33. </script>
  34. </body>
  35. </html>

发表评论

表情:
评论列表 (有 0 条评论,177人围观)

还没有评论,来说两句吧...

相关阅读

    相关 让Python随机生成颜色

    颜色的表示方式有三种:RGB、十六进制和颜色名 Python支持的颜色有:十六进制和颜色名 十六进制颜色值是和RGB有着关联的,比如这个颜色 ██████████ 纯红色