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:
1 |
var rgb = document.getElementById('color').style.backgroundColor; |
The format is as follows: rgb (225, 22, 23); then split:
1 |
var rgb = rgb.split('(')[1]; // The split result is in the format of [rgb, 225,22, 23)], and the length is an array of 2. |
Then split the string (, 22, 23) (Note: Only the number type can be converted, so use parseInt to forcibly convert the type !) :
1 |
for(var k = 0; k < 3; k++){ |
2 |
str[k] = parseInt(rgb .split(',')[k]).toString(16);// The str array stores the split data. |
Final combination:
1 |
str = '#'+str[0]+str[1]+str[2]; |
The Code is as follows:
04 |
<Title> getHexColor js/jQuery get hexadecimal color </title> |
05 |
<meta charset="utf-8" /> |
06 |
<script type="text/javascript"> |
07 |
function getHexBgColor(){ |
09 |
var rgb = document.getElementById('color').style.backgroundColor.split('('); |
10 |
for(var k = 0; k < 3; k++){ |
11 |
str[k] = parseInt(rgb[1].split(',')[k]).toString(16); |
13 |
str = '#'+str[0]+str[1]+str[2]; |
14 |
document.getElementById('color').innerHTML = str; |
16 |
function getHexColor(){ |
18 |
var rgb = document.getElementById('color').style.color.split('('); |
19 |
for(var k = 0; k < 3; k++){ |
20 |
str[k] = parseInt(rgb[1].split(',')[k]).toString(16); |
22 |
str = '#'+str[0]+str[1]+str[2]; |
23 |
document.getElementById('color').innerHTML = str; |
26 |
<style type="text/css"> |
36 |
<div style="color: #88ee22; background-color: #ef8989;" id="color"></div> |
37 |
<input onclick="getHexBgColor();" type="button" value="Get background color" /> |
38 |
<input onclick="getHexColor();" type="button" value="Get font color" /> |