html css js 生成随机颜色

起因, 目的:

整理文件,发现之前写的一个小工具。

效果图

点击按钮会生成新的格子。
html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Random Color Blocks</title>
    <style>
      .color-block {
        width: 100px;
        height: 100px;
        display: inline-block;
        margin: 5px;
      }
      #generate-button {
        justify-content: center;
        align-items: center;
        width: 350px;
        height: 80px;
        background-color: pink;
        margin-left: 300px;
        font-size: 26px; /* 增加字体大小 */
        font-weight: bold; /* 字体加粗 */
        border-radius: 5px; /* 增加圆角 */
      }

      #generate-button:hover {
        background-color: #0056b3; /* 鼠标悬停时的背景颜色 */
      }

      #color-grid {
        margin: 100px;
        border: solid 2px black;
        border-radius: 5px; /* 增加圆角 */
      }
    </style>
  </head>
  <body>
    <h1>
      <button id="generate-button">Generate New Colors</button>
    </h1>

    <div id="color-grid"></div>

    <script>
      // Function to generate a random color within the specified range
      function getRandomColor(min, max) {
        return `rgb(${Math.floor(Math.random() * (max - min + 1)) + min}, ${
          Math.floor(Math.random() * (max - min + 1)) + min
        }, ${Math.floor(Math.random() * (max - min + 1)) + min})`;
      }

      // Function to create a grid of color blocks
      function createColorGrid(size) {
        const grid = document.getElementById("color-grid");
        grid.innerHTML = ""; // Clear the grid
        for (let i = 0; i < size * size; i++) {
          const block = document.createElement("div");
          block.classList.add("color-block");
          block.style.backgroundColor = getRandomColor(10, 250);
          grid.appendChild(block);
        }
      }

      // Function to handle the button click event
      function handleButtonClick() {
        createColorGrid(9); // Start with a 3x3 grid
      }

      // Initial grid creation
      createColorGrid(9); // Start with a 3x3 grid

      // Add event listener to the button
      document
        .getElementById("generate-button")
        .addEventListener("click", handleButtonClick);
    </script>
  </body>
</html>

老哥留步,支持一下。

相关推荐
神膘护体小月半12 分钟前
css 的 clip-path 属性,绘制气泡
css
oak隔壁找我14 分钟前
JavaScript 模块化演进历程:问题与解决方案。
前端·javascript·架构
代码改变世界1008619 分钟前
像素塔防游戏:像素守卫者
css·游戏·css3·1024程序员节
烟袅1 小时前
JavaScript 变量声明报错指南:var、let、const 常见错误解析
javascript
烟袅1 小时前
告别 var!深入理解 JavaScript 中 var、let 和 const 的差异与最佳实践
javascript·面试
mapbar_front2 小时前
Electron 应用自动更新方案:electron-updater 完整指南
前端·javascript·electron
W.Buffer3 小时前
设计模式-单例模式:从原理到实战的三种经典实现
开发语言·javascript·单例模式
Mintopia4 小时前
深度伪造检测技术在 WebAIGC 场景中的应用现状
前端·javascript·aigc
BUG_Jia4 小时前
如何用 HTML 生成 PC 端软件
前端·javascript·html·桌面应用·1024程序员节
木易 士心4 小时前
CSS 样式用法大全
前端·css·1024程序员节