Ai
1 Star 0 Fork 12

NextZero/dom.js

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
toHex.js 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
Yaohaixiao 提交于 2023-12-04 19:37 +08:00 . fix: 修复 HSL 格式转 hex 的错误
import _HSLToRGB from './_HSLToRGB'
import { KEYWORDS, REG_HSL, REG_RGB, REG_HEX3, REG_HEX } from './utils/enum'
/**
* 返回将指定颜色(颜色英文名称、RGB格式或者 HSL 格式色值)转化成 16 进制色值
* ========================================================================
* @method toHex
* @since 0.4.0
* @param {String} color
* @return {String|Boolean}
*/
const toHex = (color) => {
let matches = []
let hex
let rgb
let r
let g
let b
if (!color) {
return false
}
hex = KEYWORDS[color] || color
if (REG_HEX.test(hex)) {
return hex
}
if (REG_HSL.test(hex)) {
matches = REG_HSL.exec(hex)
rgb = _HSLToRGB(
parseInt(matches[1], 10),
parseInt(matches[2], 10),
parseInt(matches[3], 10)
)
return toHex(`rgb(${rgb.join(',')})`)
} else {
matches = REG_RGB.exec(hex)
}
if (matches) {
r = matches[1]?.length === 1 ? '0' + matches[1] : Number(matches[1])
g = matches[2]?.length === 1 ? '0' + matches[2] : Number(matches[2])
b = matches[3]?.length === 1 ? '0' + matches[3] : Number(matches[3])
hex = [r.toString(16), g.toString(16), b.toString(16)].join('')
}
if (hex.length < 6) {
hex = hex.replace(REG_HEX3, '$1$1')
}
/* istanbul ignore else */
if (hex !== 'transparent' && hex.indexOf('#') < 0) {
hex = '#' + hex
}
return hex.toLowerCase()
}
export default toHex
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/nextzero/dom.js.git
git@gitee.com:nextzero/dom.js.git
nextzero
dom.js
dom.js
main

搜索帮助