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>

老哥留步,支持一下。

相关推荐
某公司摸鱼前端1 小时前
uniapp socket 封装 (可拿去直接用)
前端·javascript·websocket·uni-app
要加油哦~1 小时前
vue | 插件 | 移动文件的插件 —— move-file-cli 插件 的安装与使用
前端·javascript·vue.js
weixin-a153003083162 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
wen's3 小时前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
vvilkim3 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim4 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心4 小时前
vben 之 axios 封装
前端·javascript·学习
漫谈网络4 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
青皮桔5 小时前
CSS实现百分比水柱图
前端·css
失落的多巴胺5 小时前
使用deepseek制作“喝什么奶茶”随机抽签小网页
javascript·css·css3·html5