使用 input 标签 type=‘color'属性调出浏览器的调色板,监听 input 事件实时获取取色值,将 input 标签隐藏以应用自定义样式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <style> .palette { width: 30px; height: 30px; border-radius: 9999px; background-color: #000; } input { opacity: 0; position: absolute; overflow: hidden; height: 30px; width: 30px; } </style>
<div class="palette"> <input type="color" onChange="handleChange(event)" onInput="handleInput(event)" /> </div>
<script> const handleChange = (e) => { console.log(e.target.value) }
const handleInput = (e) => { const color = e.target.value document .querySelector('.palette') .setAttribute('style', `background-color:${color}`) } </script>
|