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>

老哥留步,支持一下。

相关推荐
GISer_Jing1 小时前
Node.js 开发实战:从入门到精通
javascript·后端·node.js
5335ld1 小时前
后端给的post 方法但是要求传表单数据格式(没有{})
开发语言·前端·javascript·vue.js·ecmascript
QDKuz2 小时前
掌握Vue2转Vue3, Options API 转 Composition API
前端·javascript·vue.js
老前端的功夫2 小时前
前端Echarts性能优化:从卡顿到流畅的百万级数据可视化
前端·javascript
进击的野人2 小时前
深入解析localStorage:前端数据持久化的核心技术
前端·javascript
Mh2 小时前
如何优雅的消除“if...else...”
前端·javascript
码银2 小时前
docsify 本地部署完整配置模板 || 将md文件放到网页上展示
html·docsify·md
火鸟22 小时前
给予虚拟成像台尝鲜版十之二,完善支持 HTML 原型模式
前端·html·原型模式·通用代码生成器·给予虚拟成像台·快速原型·rust语言
lapiii3582 小时前
[前端-React] Hook
前端·javascript·react.js
小飞大王6662 小时前
JavaScript基础知识总结(六)模块化规范
开发语言·javascript·ecmascript