JavaScript中16进制颜色与rgb颜色互相转换

16进制转 rgb

function hexToRgba(hex, opacity) {
    if (!hex) hex = '#ededed';
    let rgba = 'rgba(' + parseInt('0x' + hex.slice(1,3)) + ',' +
        parseInt('0x' + hex.slice(3,5)) + ',' +
        parseInt('0x' + hex.slice(5,7)) + ',' +
        (opacity || "1") + ')'
    return rgba
}

rgb 转 16进制

function RGBToHex(rgb) {
  if (!rgb) rgb = 'rgb(237,237,237)'  
  var regexp = /[0-9]{0,3}/g
  var res = rgb.match(regexp) // 利用正则表达式去掉多余的部分,将rgb中的数字提取
  var hexRes = '#'
  var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
  var hexArr = []
  for (let i = 0; i < res.length; i++) {
    if (res[i]) {
      if (res[i] > 16) {
        let leftIndex = (res[i] / 16) >> 0 // 向下取整
        let rightIndex = +res[i] % 16
        hexArr.push(hex[leftIndex])
        hexArr.push(hex[rightIndex])
      } else {
        hexArr.push(0)
        hexArr.push(hex[res[i]])
      }
    }
  }
  return hexRes += hexArr.join('')  // #EDEDED
}

  

posted @ 2023-08-08 11:01  蓝色精灵jah  阅读(647)  评论(0编辑  收藏  举报