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>

老哥留步,支持一下。

相关推荐
皮卡祺q6 分钟前
【算法-0】背包问题(三维+二维)
java·javascript·算法
whuhewei20 分钟前
手写Promise
开发语言·javascript·ecmascript
川冰ICE37 分钟前
JavaScript入门⑤|数组方法全攻略,map/filter/reduce三剑客
开发语言·javascript·ecmascript
threelab1 小时前
Three.js 抽象艺术着色器效果 | 三维可视化 / AI 提示词
前端·javascript·人工智能·3d·着色器
008爬虫实战录1 小时前
【码上爬】 题十八:模拟大厂加密算法, 堆栈分析找加密点,扣自执行函数,jsdom补环境
开发语言·javascript·ecmascript
skywalk81631 小时前
脚本 isMobile.js(移动设备检测库)的核心实现
开发语言·javascript·ecmascript
i_am_a_div_日积月累_1 小时前
3.contextBridge桥梁
前端·javascript·vue.js·electron
阿正的梦工坊2 小时前
【Typescript】04-数组元组枚举与字面量类型
javascript·ubuntu·typescript
神奇小汤圆2 小时前
自己用 ai 写了个链接 mysql 数据库的 mcp 工具
javascript
kgduu2 小时前
ethers.js学习笔记
javascript·笔记·学习