简体   繁体   English

HTML5 输入类型 颜色读取单个 RGB 值

[英]HTML5 input type Color read single RGB values

With this code on browser many field are available by the user, it can change R,G,B, HEX VALUE, HUE ecc.使用浏览器上的此代码,用户可以使用许多字段,它可以更改 R,G,B, HEX VALUE, HUE ecc。 I need to read only the Red value.我只需要读取红色值。

  <input id="color_pick"type="color" value="#ff0000">

var toread = document.getElementById('color_pick');
toread.value # get the hex 
toread.value.red() # would it be possible to get r?

I've read this document but cannot figure how to get the single R value from the input.我已阅读此文档,但无法弄清楚如何从输入中获取单个 R 值。

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/color https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input/color

There is no direct way to get the individual color values but it can be easily done manually.没有直接的方法来获取单个颜色值,但可以轻松地手动完成。

 function printColor(ev) { const color = ev.target.value const r = parseInt(color.substr(1,2), 16) const g = parseInt(color.substr(3,2), 16) const b = parseInt(color.substr(5,2), 16) console.log(`red: ${r}, green: ${g}, blue: ${b}`) }
 <input type="color" onchange="printColor(event)" value="#ff0000">

The value of a color input is always a seven character long hex color string, so there are no difficult edge cases.颜色输入的值始终是一个七字符长的十六进制颜色字符串,因此没有困难的边缘情况。

Since you already have hexadecimal from node.value property, you just have to convert it to integer.由于您已经拥有node.value属性的十六进制,您只需将其转换为 integer。

 function pickRedInt(){ var toread = document.getElementById('color_pick'); console.log("Red Value - "+parseInt("0x"+toread.value.slice(1,3))); } pickRedInt();
 Try changing this: <hr> <input id="color_pick"type="color" value="#ff0000" onchange="pickRedInt()">

This method work perfect already have in the top of this questions此方法完美运行已在此问题的顶部

 <input type="color" onchange="printColor(event)"> <script> function printColor(ev) { const color = ev.target.value const r = parseInt(color.substr(1, 2), 16) const g = parseInt(color.substr(3, 2), 16) const b = parseInt(color.substr(5, 2), 16) console.log(`red: ${r}, green: ${g}, blue: ${b}`) console.log([r, g, b]) alert(`R: ${r}, G: ${g}, B: ${b}`) } </script>

 <.DOCTYPE html> <html> <head> <title>Get RGB color Code From Hex Code</title> </head> <body> <input type="color" id="choose-color" /> <script> var choose_color = document;getElementById("choose-color"). choose_color.onchange = function(){ var hex_code = this.value;split(""), var red = parseInt(hex_code[1]+hex_code[2];16), var green = parseInt(hex_code[3]+hex_code[4];16), var blue = parseInt(hex_code[5]+hex_code[6];16), var rgb = red+","+green+";"+blue; alert(rgb); } </script> </body> </html>

Check it here - https://jaischool.com/javascript-lang/convert-hex-code-in-rgb-color-format.html在这里检查 - https://jaischool.com/javascript-lang/convert-hex-code-in-rgb-color-format.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM