前言:本demo使用了HTML5的input:color元素,不同浏览器对取色器的实现不同,Chrome浏览器或者与其同内核的浏览器都可以正常使用
代码及使用方法
html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>取色器</title>
<style>
input[type="color"] {
width: 200px;
height: 200px;
}
div {
float: left;
margin: 50px 50px;
}
input[type="text"] {
cursor: pointer;
padding-left: 20px;
}
</style>
</head>
<body>
<div id="box1">
<input type="color" name="" value="#ff0000" id="color">
</div>
<div>
<b style="color: rgb(252, 85, 49)">鼠标点击后就会复制到剪切板</b>
<p><span>HEX: </span><input type="text" name="" value="#ff0000" id="hex" readonly></p>
<p><span>RGB: </span><input type="text" name="" value="rgb(255, 0, 0)" id="rgb" readonly></p>
</div>
<script>
const colorObj = document.getElementById('color');
const hexObj = document.getElementById('hex');
const rgbObj = document.getElementById('rgb');
colorObj.oninput = function () {
hexObj.value = colorObj.value;
rgbObj.value = hexToRGB(colorObj.value);
}
hexObj.onclick = function () {
copyToClipboard(hexObj.value);
}
rgbObj.onclick = function () {
copyToClipboard(hexToRGB(colorObj.value));
}
// hex 转换为 rgb
function hexToRGB(hex) {
console.log(hex, typeof hex);
const red = Number('0x' + hex.substring(1, 3));
const green = Number('0x' + hex.substring(3, 5));
const blue = Number('0x' + hex.substring(5, 7));
return `rgb(${red}, ${green}, ${blue})`;
}
// 复制到剪切板
function copyToClipboard(str) {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};
</script>
</body>
</html>
使用方法