自定义颜色对照工具(快捷复制颜色十六进制编码)

该文章已生成可运行项目,

一、介绍

1.背景

由于前端、PPT、PS、给好朋友写贺卡时都需要对颜色进行处理,然而一些普通的颜色(如:赤橙黄绿青蓝紫)无法满足日常需要,所以难免要和更复杂的颜色打交道,而日常使用比较频繁的格式有RGB和十六进制编码。于是自定义了一个工具,用来记录个人比较喜欢的颜色,以便快速地查找和复制。

2.介绍

  • 该工具使用HTML代码编写,所以十分适用,无需下载任何软件即可使用
  • 该工具支持持久化存储,因此关闭网页、刷新网页不会导致数据丢失
  • 该工具无需联网,离线即可使用
  • 文字的颜色为格子颜色的补色,方便在设计时更好地利用撞色
  • 左键单击格子即可进行编辑,右键单击格子即可复制颜色的十六进制编码(超级方便!!!)

3.UI

共有五个按钮,对应操作为:新增、重置、导入、导出、重置

  • 新增:单击新增按钮,即可按序生成一个新的格子,默认十六进制码为:#ffffff
  • 重置:单击重置按钮,依次输入行列号即可将格子的颜色重置为:#ffffff
  • 导入:单击导入按钮,输入一定格式的JSON串,即可导入其它用户的色盘
  • 导出:单击导出按钮,在色盘的最底部会显示当前色盘的JSON串,可供其它用户导入
  • 重置:单击重置按钮,即会将色盘重置,谨慎点击!不可恢复!!!(但好像不刷新就不会没,这个BUG就不修复了)

4.使用

  • 新建txt类型的文件
  • 复制代码
  • 粘贴代码
  • 修改文件后缀为.html

二、源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>色盘</title>
    <style>
        button {
            margin: 10px;
            padding: 10px 20px;
            font-size: 16px;
        }

        #main {
            width: 100%;
            min-height: 85vh;
            /*background-color: #9877ec;*/
        }

        table {
            border-collapse: collapse;
            width: 95vw;
            margin-left: 2.5vw; /*居中*/
            /*background-color: #958b56;*/
        }

        tr {
            height: 10vh;
            background-color: white;
        }


        td {
            /*margin-left: 10px;*/
            border: 1px solid #000;
            /*border-radius: 20px;*/
            max-width: 12.5%;
            text-align: right;
            padding-top: 8vh;
            cursor: pointer;
            background-color: rgb(255, 255, 255);
            position: relative;
        }
        .first{
            border: 1px solid #000;
            text-align: center;
            margin-top: 9vh;
            cursor: pointer;
            background-color: rgb(255, 255, 255);
            position: relative;
            padding-top: 0;
        }
        #toast {
            visibility: hidden;
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background-color: rgba(0, 0, 0, 0.75);
            color: white;
            padding: 10px;
            border-radius: 5px;
            font-size: 16px;
        }
        textarea{
            margin-left: 5%;
            width: 90%;
        }


    </style>
</head>
<body>
<div id="toast"></div>
<button id="addCellBtn">新增一个格子</button>
<button id="deleteCellBtn">重置一个格子</button>
<button id="import">导入</button>
<button id="export">导出</button>
<button id="reset">重置</button>
<div id="main">
    <table>
        <tr>
            <td class="first">1</td>
            <td class="first">2</td>
            <td class="first">3</td>
            <td class="first">4</td>
            <td class="first">5</td>
            <td class="first">6</td>
            <td class="first">7</td>
            <td class="first">8</td>
        </tr>
    </table>
    <table id="table" style="table-layout: fixed;">

    </table>
</div>
<textarea id="exportText" style="visibility: hidden">导出</textarea>


<script>
    const table = document.getElementById('table');
    const addCellBtn = document.getElementById('addCellBtn');
    const deleteCellBtn = document.getElementById('deleteCellBtn');
    const importBtn=document.getElementById("import");
    const exportBtn=document.getElementById("export");
    const resetBtn=document.getElementById("reset");
    const exportText=document.getElementById("exportText");
    let totalCells = 0;

    // 加载持久化数据
    function loadTable() {
        const storedData = JSON.parse(localStorage.getItem('tableData')) || [];
        storedData.forEach((row, rowIndex) => {
            const tableRow = table.insertRow();
            row.forEach((cellData, cellIndex) => {
                const cell = tableRow.insertCell(cellIndex);
                cell.style.backgroundColor = cellData.backgroundColor;
                cell.style.color=cellData.color;
                cell.textContent = cellData.text;
                cell.style.width="12.5%"
                bindCellEvents(cell, rowIndex, cellIndex);
            });
        });
        totalCells = storedData.flat().length;
    }

    // 保存表格到 localStorage
    function saveTable() {
        const data = [];
        //从1开始,第一行是序号
        for (let i = 0; i < table.rows.length; i++) {
            const row = table.rows[i];
            const rowData = [];
            for (let j = 0; j < row.cells.length; j++) {
                const cell = row.cells[j];
                rowData.push({
                    text: cell.textContent,
                    backgroundColor: cell.style.backgroundColor,
                    color:cell.style.color
                });
            }
            data.push(rowData);
        }
        localStorage.setItem('tableData', JSON.stringify(data));
    }

    // 添加新的单元格
    addCellBtn.addEventListener('click', () => {
        totalCells++;
        const rows = Math.ceil(totalCells / 8);
        while (table.rows.length < rows) {
            table.insertRow();
        }
        const row = table.rows[rows - 1];
        const cell = row.insertCell(row.cells.length);
        cell.style.backgroundColor = getRandomColor();
        cell.style.color =getComplementaryColor(cell.style.backgroundColor);
        cell.textContent = `${rgbToHex(cell.style.backgroundColor)}`;
        bindCellEvents(cell, rows - 1, row.cells.length - 1);
        saveTable();
    });

    // 删除现有的单元格
    deleteCellBtn.addEventListener('click', () => {
        let rowIndex = prompt("请输入行号 (从1开始):");
        let cellIndex = prompt("请输入列号 (从1开始):");
        deleteCell(rowIndex, cellIndex);
    });

    //导入
    importBtn.addEventListener('click',()=>{
        const str = prompt(`请输入链接`);
        if(str!==""){
            localStorage.clear();
            table.innerHTML = '';
            const storedData = JSON.parse(str);
            storedData.forEach((row, rowIndex) => {
                const tableRow = table.insertRow();
                row.forEach((cellData, cellIndex) => {
                    const cell = tableRow.insertCell(cellIndex);
                    cell.style.backgroundColor = cellData.backgroundColor;
                    cell.style.color=cellData.color;
                    cell.textContent = cellData.text;
                    cell.style.width="12.5%"
                    bindCellEvents(cell, rowIndex, cellIndex);
                });
            });
            totalCells = storedData.flat().length;
            saveTable();
        }
    })

    //导出
    exportBtn.addEventListener('click',()=>{
        exportText.style.visibility="visible";
        exportText.innerText=localStorage.getItem('tableData') || [];
    })

    resetBtn.addEventListener('click',()=>{
        if (confirm("重置操作不可逆!!!您确定要取消吗?")) {
            localStorage.clear();
            loadTable();
        }

    })

    // 删除单元格,序号从1开始,实际只是让该格子变为默认颜色
    function deleteCell(rowIndex, cellIndex) {
        rowIndex--;
        cellIndex--;
        const row = table.rows[rowIndex];
        const cell = row.cells[cellIndex];
        cell.style.backgroundColor=getRandomColor();
        cell.style.color =getComplementaryColor(cell.style.backgroundColor);
        cell.textContent = `${rgbToHex(cell.style.backgroundColor)}`;
        saveTable();
    }

    // 绑定单元格事件
    function bindCellEvents(cell, rowIndex, cellIndex) {
        //左键
        cell.addEventListener('click', () => showColorEditor(cell, rowIndex, cellIndex));
        //右键
        cell.addEventListener('contextmenu', function(event) {
            event.preventDefault();  // 阻止默认的右键菜单
            // 获取单元格内容
            const cellText = cell.textContent;

            // 使用 Clipboard API 复制文本到剪贴板
            navigator.clipboard.writeText(cellText).then(() => {
                showToast(`已复制: ${cellText}`);// 提示已复制的内容
            }).catch(err => {
                console.error('复制失败:', err);
            });
        });
    }


    function showToast(message) {
        const toast = document.getElementById('toast');

        toast.style.visibility = 'visible';
        toast.textContent=message;
        // 3秒后自动隐藏
        setTimeout(() => {
            toast.style.visibility = 'hidden';
        }, 3000); // 3000 毫秒 (3秒)
    }

    // 显示颜色编辑框
    function showColorEditor(cell, rowIndex, cellIndex) {
        const currentColor = rgbToHex(cell.style.backgroundColor);
        const newColor = prompt(`当前颜色: ${currentColor}\n请输入新的颜色 (十六进制格式 #RRGGBB):`);
        if (newColor && isValidHexColor(newColor)) {
            cell.textContent=newColor;
            cell.style.backgroundColor = newColor;
            cell.style.color =getComplementaryColor(newColor);
            saveTable();
        } else if (newColor) {
            alert("无效的颜色值!");
        }
    }

    // 随机生成 RGB 颜色
    function getRandomColor() {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        // return `rgb(${r}, ${g}, ${b})`;
        return `rgb(255, 255, 255)`;
    }

    function getComplementaryColor(color){
        // 如果颜色是十六进制格式,先转换为 RGB
        if (color.startsWith('#')) {
            color = hexToRgb(color);
        }
        // 提取 RGB 值
        let rgb = color.match(/\d+/g).map(Number);  // 转换为数组:[r, g, b]

        // 计算互补色
        let compRgb = rgb.map(value => 255 - value);

        // 转换为 rgb(互补色)
        return `rgb(${compRgb[0]}, ${compRgb[1]}, ${compRgb[2]})`;
    }

    // 验证十六进制颜色
    function isValidHexColor(color) {
        return /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(color);
    }

    // RGB 转 十六进制颜色
    function rgbToHex(rgb) {
        const result = rgb.match(/\d+/g);
        return `#${result.map(x => parseInt(x).toString(16).padStart(2, '0')).join('')}`;
    }

    function hexToRgb(hex) {
        let r = parseInt(hex.slice(1, 3), 16);
        let g = parseInt(hex.slice(3, 5), 16);
        let b = parseInt(hex.slice(5, 7), 16);
        return `rgb(${r}, ${g}, ${b})`;
    }
    // 页面加载时初始化表格
    loadTable();
</script>
</body>
</html>

三、导入

为了更加方便的使用,下列数据中预置了一些颜色,方便大家使用

[[{"text":"#123456","backgroundColor":"rgb(18, 52, 86)","color":"rgb(237, 203, 169)"},{"text":"#F39F74","backgroundColor":"rgb(243, 159, 116)","color":"rgb(12, 96, 139)"},{"text":"#A9A7BC","backgroundColor":"rgb(169, 167, 188)","color":"rgb(86, 88, 67)"},{"text":"#666699","backgroundColor":"rgb(102, 102, 153)","color":"rgb(153, 153, 102)"},{"text":"#5E7C85","backgroundColor":"rgb(94, 124, 133)","color":"rgb(161, 131, 122)"},{"text":"#483D8B","backgroundColor":"rgb(72, 61, 139)","color":"rgb(183, 194, 116)"},{"text":"#F08B4F","backgroundColor":"rgb(240, 139, 79)","color":"rgb(15, 116, 176)"},{"text":"#89B0D4","backgroundColor":"rgb(137, 176, 212)","color":"rgb(118, 79, 43)"}],[{"text":"#555555","backgroundColor":"rgb(85, 85, 85)","color":"rgb(170, 170, 170)"},{"text":"#707070","backgroundColor":"rgb(112, 112, 112)","color":"rgb(143, 143, 143)"},{"text":"#898989","backgroundColor":"rgb(137, 137, 137)","color":"rgb(118, 118, 118)"},{"text":"#A0A0A0","backgroundColor":"rgb(160, 160, 160)","color":"rgb(95, 95, 95)"},{"text":"#8CAE58","backgroundColor":"rgb(140, 174, 88)","color":"rgb(115, 81, 167)"},{"text":"#A6C6B0","backgroundColor":"rgb(166, 198, 176)","color":"rgb(89, 57, 79)"},{"text":"#F8D1C5","backgroundColor":"rgb(248, 209, 197)","color":"rgb(7, 46, 58)"},{"text":"#F4B048","backgroundColor":"rgb(244, 176, 72)","color":"rgb(11, 79, 183)"}],[{"text":"#99D1D3","backgroundColor":"rgb(153, 209, 211)","color":"rgb(102, 46, 44)"},{"text":"#6EC3C9","backgroundColor":"rgb(110, 195, 201)","color":"rgb(145, 60, 54)"},{"text":"#00B2BF","backgroundColor":"rgb(0, 178, 191)","color":"rgb(255, 77, 64)"},{"text":"#00A6AD","backgroundColor":"rgb(0, 166, 173)","color":"rgb(255, 89, 82)"},{"text":"#98D0B9","backgroundColor":"rgb(152, 208, 185)","color":"rgb(103, 47, 70)"},{"text":"#67BF7F","backgroundColor":"rgb(103, 191, 127)","color":"rgb(152, 64, 128)"},{"text":"#00AE72","backgroundColor":"rgb(0, 174, 114)","color":"rgb(255, 81, 141)"},{"text":"#00A06B","backgroundColor":"rgb(0, 160, 107)","color":"rgb(255, 95, 148)"}],[{"text":"#BFCAE6","backgroundColor":"rgb(191, 202, 230)","color":"rgb(64, 53, 25)"},{"text":"#94AAD6","backgroundColor":"rgb(148, 170, 214)","color":"rgb(107, 85, 41)"},{"text":"#7388C1","backgroundColor":"rgb(115, 136, 193)","color":"rgb(140, 119, 62)"},{"text":"#426EB4","backgroundColor":"rgb(66, 110, 180)","color":"rgb(189, 145, 75)"},{"text":"#A095C4","backgroundColor":"rgb(160, 149, 196)","color":"rgb(95, 106, 59)"},{"text":"#8273B0","backgroundColor":"rgb(130, 115, 176)","color":"rgb(125, 140, 79)"},{"text":"#635BA2","backgroundColor":"rgb(99, 91, 162)","color":"rgb(156, 164, 93)"},{"text":"#511F90","backgroundColor":"rgb(81, 31, 144)","color":"rgb(174, 224, 111)"}],[{"text":"#FEEBD0","backgroundColor":"rgb(254, 235, 208)","color":"rgb(1, 20, 47)"},{"text":"#FCE0A6","backgroundColor":"rgb(252, 224, 166)","color":"rgb(3, 31, 89)"},{"text":"#F9CC76","backgroundColor":"rgb(249, 204, 118)","color":"rgb(6, 51, 137)"},{"text":"#F3C246","backgroundColor":"rgb(243, 194, 70)","color":"rgb(12, 61, 185)"},{"text":"#FCDAD5","backgroundColor":"rgb(252, 218, 213)","color":"rgb(3, 37, 42)"},{"text":"#F5A89A","backgroundColor":"rgb(245, 168, 154)","color":"rgb(10, 87, 101)"},{"text":"#EE7C6B","backgroundColor":"rgb(238, 124, 107)","color":"rgb(17, 131, 148)"},{"text":"#E54646","backgroundColor":"rgb(229, 70, 70)","color":"rgb(26, 185, 185)"}],[{"text":"#ffffff","backgroundColor":"rgb(255, 255, 255)","color":"rgb(0, 0, 0)"}]]

对应效果如下:


如果觉得有用或者有意思的话,不妨点个赞吧,这会让我十分幸福的!ヾ(●゜▽゜●)♡

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值