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 天前
HTML常用标签总结
前端·html
唐叔在学习1 天前
e.preventDefault()到底怎么用?
前端·javascript
Highcharts.js1 天前
Highcharts React v4.2.1 正式发布:更自然的React开发体验,更清晰的数据处理
linux·运维·javascript·ubuntu·react.js·数据可视化·highcharts
木斯佳1 天前
鸿蒙开发入门指南:前端开发者快速掌握常用布局
前端·css
炽烈小老头1 天前
前端最最最基础的基础HTML基础
前端·html
new code Boy1 天前
Vue2转Vue3速查表
前端·javascript·vue.js
紫_龙1 天前
最新版vue3+TypeScript开发入门到实战教程之toRefs与toRef实用技巧
前端·javascript·typescript
大家的林语冰1 天前
Vite 第 1 个 Rolldown 稳定版正式发布,前端构建又一波“工业革命“
前端·javascript·vite
嘉琪0011 天前
前端数组核心方法(高级视角 + 场景 + 精简)——————2026 0309
开发语言·前端·javascript
怪侠_岭南一只猿1 天前
爬虫阶段一实战练习题二:爬取当当网图书列表
css·爬虫·python·html