Using JavaScript to convert hexadecimal color values to RGB, javascriptrgb
This article describes how to convert hexadecimal color values to RGB using JavaScript. Share it with you for your reference. The specific implementation method is as follows:
Copy codeThe Code is as follows: <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Title> hexadecimal color value to RGB </title>
<Style>
* {Margin: 0; padding: 0; font-family: 'Microsoft yahei '}
. Replace {width: 400px; height: 210px; margin: 0 auto; padding-top: 40px ;}
. Title {text-align: center; display: block}
Form {width: 200px; margin: 30px auto ;}
Input {outline: none ;}
Input [type = "button"] {cursor: pointer ;}
</Style>
<Script>
Function hexToR (h ){
Return parseInt (cutHex (h). substring (0, 2), 16)
}
Function hexToG (h ){
Return parseInt (cutHex (h). substring (2, 4), 16)
}
Function hexToB (h ){
Return parseInt (cutHex (h). substring (4, 6), 16)
}
Function cutHex (h ){
Return h. charAt (0) = "#"? H. substring (1, 7): h
}
Function setBgColorById (id, sColor ){
Var elems;
If (document. getElementById ){
If (elems = document. getElementById (id )){
If (elems. style) elems. style. backgroundColor = sColor;
}
}
}
</Script>
</Head>
<Body>
<Div class = "replace">
<Span class = "title"> convert the native hexadecimal color value of JavaScript to the RGB value </span>
<Form name = "rgb">
<Input value = "ffffff" maxlength = "7" size = "16" name = "hex"/>
<Input onclick = "setBgColorById ('colorsample', this. form. hex. value );
This. form. r. value = hexToR (this. form. hex. value );
This. form. g. value = hexToG (this. form. hex. value );
This. form. B. value = hexToB (this. form. hex. value); "value =" Conversion "type =" button "name =" btn "/>
<Br/>
R: <input style = "width: 30px" size = "3" name = "r"/>
G: <input style = "width: 30px" size = "3" name = "g"/>
B: <input style = "width: 30px" size = "3" name = "B"/>
</Form>
</Div>
</Body>
</Html>
Shows the running effect:
I hope this article will help you design javascript programs.