简体   繁体   中英

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. 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.

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.

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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