To obtain the background color and font color of a webpage, follow these steps:
Idea: the rgb color is obtained by obtaining the color attribute value, which is not what we want. Therefore, we need to replace the rgb color with the hexadecimal color to first obtain the rgb color:
Copy codeThe Code is as follows:
Var rgb = document. getElementById ('color'). style. backgroundColor;
The format is as follows: rgb (225, 22, 23); then split:
Copy codeThe Code is as follows:
Var rgb = rgb. split (') [1]; // an array of 2 in the format of [rgb, 225,22, 23)] after splitting
Then split the string (, 22, 23) (Note: Only the number type can be converted, so use parseInt to forcibly convert the type !) :
Copy codeThe Code is as follows:
For (var k = 0; k <3; k ++ ){
Str [k] = parseInt (rgb. split (',') [k]). toString (16); // The str array stores the split data.
}
Final combination:
Copy codeThe Code is as follows:
Str = '#' + str [0] + str [1] + str [2];
The Code is as follows:
Copy codeThe Code is as follows:
<! DOCTYPE html>
<Html>
<Head>
<Title> getHexColor js/jQuery get hexadecimal color </title>
<Meta charset = "UTF-8"/>
<Script type = "text/javascript">
Function getHexBgColor (){
Var str = [];
Var rgb = document. getElementById ('color'). style. backgroundColor. split ('(');
For (var k = 0; k <3; k ++ ){
Str [k] = parseInt (rgb [1]. split (',') [k]). toString (16 );
}
Str = '#' + str [0] + str [1] + str [2];
Document. getElementById ('color'). innerHTML = str;
}
Function getHexColor (){
Var str = [];
Var rgb = document. getElementById ('color'). style. color. split ('(');
For (var k = 0; k <3; k ++ ){
Str [k] = parseInt (rgb [1]. split (',') [k]). toString (16 );
}
Str = '#' + str [0] + str [1] + str [2];
Document. getElementById ('color'). innerHTML = str;
}
</Script>
<Style type = "text/css">
# Color {
Width: 200px;
Height: 200px;
Line-height: 200px;
Text-align: center;
}
</Style>
</Head>
<Body>
<Div style = "color: #88ee22; background-color: # ef8989;" id = "color"> </div>
<Input onclick = "getHexBgColor ();" type = "button" value = "get background color"/>
<Input onclick = "getHexColor ();" type = "button" value = "Get font color"/>
</Body>
</Html>