[html local tool] html+JavaScript implements a nice-looking color code query, supports query, conversion, color selector and color code comparison table

foreword

I believe that you will often use color codes in your daily work. For example, if you want to find a good-looking color, or you have a color code but don’t know what color the code is, then we can use the color code comparison table or Check out the color code.

Of course, you can also use screenshot software or color picker or PS to view, but this is not very convenient and comprehensive after all. At this time, we can write a color code comparison table by ourselves, and then store it in the tab bar, and open it at any time when using it.

At this time, some people may say that there are many such websites that can be easily searched online. Yes, there are indeed many, but this is someone else's website after all and cannot be customized. The so-called customization is to list the colors that you often use in color blocks, and open it the next time you use it, you will know what the specific color is, and then you can copy the color code and use it. Otherwise, I didn’t remember the code every time I used it, and I was confused when I went to the website to find it, and then I had to look through the previous usage records to see which color code it was.

So it is very convenient to write an html by yourself and write the colors you often use.

Effect

Let's take a look at the rendering first.

insert image description here

insert image description here

The top two input boxes are the conversion between rgb and hex; after entering the color value, the small square behind the input box will automatically change to the corresponding color, click on the color block, and the color code will be copied automatically.

The middle piece is the color selector, and the color block area on the left is to put the color code that you often use. Click the color block directly to automatically copy the color code, and the color selector and the two input boxes on the right will also automatically Select/output the corresponding color.

The bottom block is the color collection, click the color block or the text next to it, you can directly copy the color code.


Click to copy the color code:

insert image description here

insert image description here

the code

Next is the code. There are a lot of codes, mainly because the bottom color block is hard-coded on the html, unlike the commonly used color block above which is a dynamically created element. Because considering that there are many colors in this encyclopedia, there are more than 500 td elements. If this is dynamically created, I am afraid that the page will be stuck, so I directly write it to death. Here, I didn’t write the more than 500 td elements. You can go to the resource download or go to the git link I gave to download the complete one.

<!DOCTYPE html>
<html>
<head>
  <title>RGB颜色查询对照表</title>
  <style>
    *{
      
      
        margin: 0 auto;
    }
    body{
      
      
      background-color: #68768a;
    }
	/* 设置滚动条的样式 */
	::-webkit-scrollbar {
      
      
		width:5px;
	}
	/* 滚动槽 */
	::-webkit-scrollbar-track {
      
      
		-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3);
		border-radius:10px;
	}
	/* 滚动条滑块 */
	::-webkit-scrollbar-thumb {
      
      
		border-radius:10px;
		background:rgba(0,0,0,0.1);
		-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.5);
	}
	::-webkit-scrollbar-thumb:window-inactive {
      
      
		background:rgba(30, 144, 255,0.4);
	}
    .main{
      
      
      position: relative;
      top: 30px;
      width: 90%;
      text-align: center;
    }
    .RGB转HEX{
      
      
      margin-bottom: 30px;
    }
    label{
      
      
      color: #00bfff;
      font-size: 1.5em;
    }
    #色值转换 input{
      
      
      width: 300px;
      height: 30px;
      padding: 10px;
      font-size: 18px;
      border-radius: 10px;
      border: none;
    }
    .color-block {
      
      
      display: inline-block;
      width: 48px;
      height: 48px;
      border: 1px solid #1e90ff;
      vertical-align: top;
    }
    #颜色选择器{
      
      
      margin-top: 40px;
    }
    ul{
      
      
        display: flex;
        flex-wrap: wrap;
        width: 250px;
        float: left;
        margin-left: 35%;
    }
    li{
      
      
        list-style: none;
        width: 20px;
        height: 20px;
        margin: 2.5px;
        cursor: pointer;
    }
    .颜色选择器{
      
      
      float: left;
      margin-left: 20px;
    }
    #colorPicker{
      
      
      height: 48px;
      vertical-align: top;
      display: inline-block;
    }
    #colorInputRgb, #colorInputHex{
      
      
      width: 150px;
      height: 30px;
      padding: 10px;
      font-size: 18px;
      border-radius: 10px;
      border: none;
      display: inherit;
      margin-top: 20px;
    }
	#颜色大全{
      
      
		margin-top: 450px;
	}
	td:nth-child(odd) {
      
      
	  height:30px;
	  width:30px;
	}
	td:nth-child(even) {
      
      
	  color: #005caf;
	  font: 12px/18px Verdana;
	}
	td:hover{
      
      
	  cursor: pointer
	}
  </style>
  
  <style type="text/css">
    /*----------------------------------------- 设置消息弹框的样式 --------------------------------------*/
    /*预定义样式,通过js动态生成dom时,加上指定类名*/
    .dpn-message {
      
      
      font-family: "\5FAE\8F6F\96C5\9ED1", Helvetica, sans-serif;
      font-size: 12px;
      z-index: 99999;
    }
    
    .dpn-message {
      
      
      box-sizing: border-box;
      position: fixed;
      top: -200px;
      left: 50%;
      transform: translateX(-50%);
      z-index: 99999;
      padding: 15px;
      padding-right: 32px;
      min-width: 20%;
      max-width: 50%;
      border-radius: 4px;
      transition: top .3s;
    }
    
    /*info 消息*/
    .dpn-message.dpn-info {
      
      
      background: #EDF2FC;
      border: 1px solid #EBEEF5;
      color: #909399;
    }
    
    /*success消息*/
    .dpn-message.dpn-success {
      
      
      background: #f0f9eb;
      border: 1px solid #54f006;
      color: #67C23A;
    }
    
    /*error消息*/
    .dpn-message.dpn-error {
      
      
      background: #fef0f0;
      border: 1px solid #fde2e2;
      color: #F56C6C;
    }
    /*warning消息*/
    
    .dpn-message.dpn-warning {
      
      
      background: #fdf6ec;
      border: 1px solid #faecd8;
      color: #E6A23C;
    }
    
    .dpn-message .dpn-close {
      
      
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      font-style: normal;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="main">
    <div id="色值转换">
      <div class="RGB转HEX">
        <label>RGB转HEX:</label>
        <input type="text" id="rgbInput" onblur="convertRGBtoHEX()" oninput="convertRGBtoHEX()" placeholder="255,255,255"/>
        <div id="rgbToHexColor" class="color-block"></div>
      </div>
  
      <div class="HEX转RGB">
        <label>HEX转RGB:</label>
        <input type="text" id="hexInput" onblur="convertHEXtoRGB()" oninput="convertHEXtoRGB()" placeholder="000 或 000000"/>
        <div id="hexToRgbColor" class="color-block"></div>
      </div>
    </div>
  
    <div id="颜色选择器">
        <ul id="color-ur"></ul>
        <div class="颜色选择器">
          <input type="color" id="colorPicker" onchange="updateColorPicker()" />
          <input type="text" id="colorInputRgb" oninput="updateColorInputRgb()" placeholder="rgb颜色值"/>
          <input type="text" id="colorInputHex" oninput="updateColorInputHex()" placeholder="hex颜色值"/>
        </div>
    </div>
	
	<div id="颜色大全">
		<table cellspacing="3">
			<!-- 这里省略颜色大全tbody -->
		</table>
	</div>
	
  </div>
  

  <!-- 动态创建消息弹框 -->
  <script type="text/javascript">
    class MessageBox {
      
      
      constructor(options) {
      
      
        // 把传递进来的配置信息挂载到实例上(以后可以基于实例在各个方法各个地方拿到这个信息)
        for(let key in options) {
      
      
          if(!options.hasOwnProperty(key)) break;
          this[key] = options[key];
        }
  
        // 开始执行
        this.init();
      }
      // 初始化:通过执行INIT控制逻辑的进行
      init() {
      
      
        if(this.status === "message") {
      
      
          this.createMessage();
          this.open();
          return;
        }
  
      }
      // 创建元素
      createMessage() {
      
      
        this.messageBox = document.createElement('div');
        this.messageBox.className = `dpn-message dpn-${ 
        this.type}`;
        this.messageBox.innerHTML = `
        ${ 
        this.message}
        <i class="dpn-close">X</i>
      `;
        document.body.appendChild(this.messageBox);
  
        // 基于事件委托监听关闭按钮的点击
        this.messageBox.onclick = ev => {
      
      
          let target = ev.target;
          //判断点击的元素是否为关闭按钮
          if(target.className === "dpn-close") {
      
      
            // 点击的是关闭按钮
            this.close();
          }
        };
  
        // 钩子函数
        this.oninit();
      }
  
      // 控制显示
      open() {
      
      
        if(this.status === "message") {
      
      
          let messageBoxs = document.querySelectorAll('.dpn-message'),
            len = messageBoxs.length;
          //计算新弹出的messageBox的Y轴偏移量
          this.messageBox.style.top = `${ 
        len===1 ? 20:20+(len-1)*70}px`;
  
          // 如果duration不为零,控制自动消失
          this.autoTimer = setTimeout(() => {
      
      
            this.close();
          }, this.duration);
  
          // 钩子函数
          this.onopen();
          return;
        }
      }
      // 控制隐藏
      close() {
      
      
        if(this.status === "message") {
      
      
          clearTimeout(this.autoTimer);
          this.messageBox.style.top = '-200px';
          let anonymous = () => {
      
      
            document.body.removeChild(this.messageBox);
            // 钩子函数
            this.onclose();
          };
          this.messageBox.addEventListener('transitionend', anonymous);
          return;
        }
  
      }
    }
  
    //全局对象上挂载该方法
    window.messageplugin = function(options = {
       
       }) {
      
      
      //允许只传入字符串,对其进行对象格式处理
      if(typeof options === "string") {
      
      
        options = {
      
      
          message: options
        };
      }
      //用户提供的配置覆盖默认配置项
      options = Object.assign({
      
      
        status: 'message',
        message: '我是默认信息',
        type: 'info',
        duration: 3000,
        //生命周期钩子
        oninit() {
      
      },
        onopen() {
      
      },
        onclose() {
      
      },
      }, options);
      return new MessageBox(options);
    };
  </script>
  
  <script>
    /*-------------------------------------------- 颜色转换 --------------------------------------------*/

	let rgbToHexColor = document.getElementById('rgbToHexColor');
    let hexToRgbColor = document.getElementById("hexToRgbColor");

    function rgbToHex(rgb) {
      
      
      //适配了中英文逗号
      var parsedRgb = /(\d{1,3})[\s,,]+(\d{1,3})[\s,,]+(\d{1,3})/g.exec(rgb);
      var r = parseInt(parsedRgb[1]);
      var g = parseInt(parsedRgb[2]);
      var b = parseInt(parsedRgb[3]);

      var hexR = ("0" + r.toString(16)).slice(-2);
      var hexG = ("0" + g.toString(16)).slice(-2);
      var hexB = ("0" + b.toString(16)).slice(-2);

      return "#" + hexR + hexG + hexB;
    }

    function hexToRgb(hex) {
      
      
      var parsedHex = /^#?([\da-f]{1,2})([\da-f]{1,2})([\da-f]{1,2})$/i.exec(hex);
      var r = parseInt(parsedHex[1], 16);
      var g = parseInt(parsedHex[2], 16);
      var b = parseInt(parsedHex[3], 16);

      if (parsedHex[1].length === 1) {
      
      
        r = r * 17;
        g = g * 17;
        b = b * 17;
      }
      return r + ", " + g + ", " + b;
    }

	// rgb转hex,将hex输入框的值设置为hex码,同时设置两个色块的颜色
    function convertRGBtoHEX() {
      
      
      var rgbInput = document.getElementById("rgbInput").value;
      var hexColor = rgbToHex(rgbInput);
      document.getElementById("rgbToHexColor").style.background = hexColor;
	  document.getElementById("hexToRgbColor").style.background = hexColor;
      document.getElementById("hexInput").value = hexColor;
    }

	// hex转rgb,将rgb输入框的值设置为rgb,同时设置两个色块的颜色
    function convertHEXtoRGB() {
      
      
      var hexInput = document.getElementById("hexInput").value;
      var rgbColor = hexToRgb(hexInput);
      document.getElementById("hexToRgbColor").style.background = "rgb(" + rgbColor + ")";
	  document.getElementById("rgbToHexColor").style.background = "rgb(" + rgbColor + ")";
      document.getElementById("rgbInput").value = "rgb(" + rgbColor + ")";
    }

	// 单击色块时,复制颜色码(rgb转hex色块的复制hex码)
    rgbToHexColor.onclick = function(e){
      
      
		let rgb = e.target.style.backgroundColor;
		if(rgb){
      
      
			let hex = rgbToHex(rgb);
			// 执行复制
			navigator.clipboard.writeText(hex).then(function() {
      
      
				messageplugin({
      
      
					message: "复制成功,"+hex,
					type: "success"
				});
			}).catch(function(error) {
      
      
				console.error('无法复制文本:', error);
			});
		}
    }

	// 单击色块时,复制颜色码(hex转rgb色块的复制rgb码)
    hexToRgbColor.onclick = function(e){
      
      
		let rgb = e.target.style.backgroundColor;
		if(rgb){
      
      
			// 执行复制
			navigator.clipboard.writeText(rgb).then(function() {
      
      
				messageplugin({
      
      
					message: "复制成功,"+rgb,
					type: "success"
				});
			}).catch(function(error) {
      
      
				console.error('无法复制文本:', error);
			});
		}
    }

    /*-------------------------------------------- 颜色选择 --------------------------------------------*/

    let colorUl=document.getElementById('color-ur');
    let colorPicker = document.getElementById("colorPicker");
    let colorInputRgb = document.getElementById("colorInputRgb");
    let colorInputHex = document.getElementById("colorInputHex");
    let 颜色大全 = document.getElementById("颜色大全");

    /*------------------------------------------ 常用颜色大全 ------------------------------------------*/
    let colorArr = [
      "#000000","#434343","#ffffff","#980000","#ff0000","#ff9900","#ffff00","#DDD23B","#CA7A2C","#BEC23F",
      "#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff","#e6b8af","#f4cccc","#fce5cd","#fff2cc",
      "#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc","#dd7e6b","#ea9999","#f9cb9c","#ffe599",
      "#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd","#cc4125","#e06666","#f6b26b","#ffd966",
      "#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0","#a61c00","#cc0000","#e69138","#f1c232",
      "#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79","#660000","#7f6000","#274e13","#0c343d",
      "#1c4587","#073763","#20124d","#68768a","#1e90ff","#00bfff","#C7802D","#48c0a4","#549688","#69b0ac",
      "#91ad70","#7398Ab","#b4caa0","#5dac81","#376b6d","#91b493","#68b4b0","#1B813E","#3d6167","#005CAF",
      "#2D6D4B","#24936E","#00AA90","#86c166","#838A2D","#90B44B","#66BAB7","#268785","#70B9DE","#33A6B8",
      "#1E88A8","#008947","#2EA9DF","#F8C3CD","#E16B8C","#DC9FB4","#F4A7B9","#B5495B","#E87A90","#D05A6E",
      "#DB4D6D","#D0104C","#EB7A77","#CB4042","#AB3B3A","#994639","#F19483","#B54434","#F17C67","#E83015",
      "#F75C2F","#F05E1C","#ED784A","#FB9966","#D75455","#9F353A","#E3916E","#C73E3A","#C46243","#E8B647",
      "#F6C555","#FBE251","#FFB11B","#FC9F4D","#FAD689","#FFC408","#F9BF45","#E9CD4C","#EFBB24","#D9AB42"
    ];

    // 动态添加li
    function iniColorPicker(){
      
      
      let html = '';
      let self = this;
      for(let i=0;i<colorArr.length;i++){
      
      
        html+= '<li  style="background:'+
        colorArr[i]+'">&nbsp;</li>';
      }
      colorUl.innerHTML=html;
    }
    iniColorPicker();

    // 颜色选择器中选择颜色时,将颜色值设置到input文本框中
    function updateColorPicker() {
      
      
      let hex = colorPicker.value;
      let rgb = hexToRgb(hex);
      colorInputRgb.value = "rgb(" + rgb + ")";
      colorInputHex.value = hex;
    }

    // 当rgb框输入了颜色值时,设置颜色选择器的值
    function updateColorInputRgb() {
      
      
      let rgb = colorInputRgb.value;
      let hex = rgbToHex(rgb);
      colorPicker.value = hex;
      colorPicker.style.backgroundColor = hex;
      colorInputHex.value = hex;
    }

    // 当hex框输入了颜色值时,设置颜色选择器的值
    function updateColorInputHex() {
      
      
      let hex = colorInputHex.value;
      let rgb = hexToRgb(hex);
      hex = rgbToHex(rgb);
      colorPicker.value = hex;
      colorPicker.style.backgroundColor = hex;
      colorInputRgb.value = "rgb(" + rgb + ")";
    }

    // 单击常用颜色时,设置颜色选择器的值、input文本框的值
    colorUl.onclick = function(e){
      
      
      if(e.target.tagName.toLowerCase() === 'li'){
      
      
        let rgb = e.target.style.backgroundColor;
        let hex = rgbToHex(rgb);
        colorInputRgb.value = rgb;
        colorInputHex.value = hex;
        colorPicker.value = hex;
        colorPicker.style.backgroundColor = hex;
        // 执行复制
        navigator.clipboard.writeText(hex).then(function() {
      
      
          messageplugin({
      
      
            message: "复制成功,"+hex,
            type: "success"
          });
        }).catch(function(error) {
      
      
          console.error('无法复制文本:', error);
        });
      }
    }

	// 单击表格的td元素时,复制元素的hex值
	颜色大全.onclick = function(e){
      
      
      if(e.target.tagName.toLowerCase() === 'td'){
      
      
		var td = e.target;
		// 获取色块td的bgcolor属性的值
		var hex = td.getAttribute('bgcolor');
		if(hex === null){
      
       // 如果值为null,说明单击的不是色块td,而是文字td
			hex = td.innerHTML; // 则直接获取文字td的innerHTML
		}
        // 执行复制
        navigator.clipboard.writeText(hex).then(function() {
      
      
          messageplugin({
      
      
            message: "复制成功,"+hex,
            type: "success"
          });
        }).catch(function(error) {
      
      
          console.error('无法复制文本:', error);
        });
      }
    }

  </script>
</body>
</html>

at last

If you set common colors, you can set your own common colors in the colorArr array of common colors.

Gitee link here

All codes are only in one html file, which can be copied and saved directly, and then opened with a browser. After opening, save it to the browser tab bar, which is very convenient for future use.

Guess you like

Origin blog.csdn.net/weixin_43165220/article/details/131708519