To obtain the background color and font color of the web page, the method is as follows:
Thought: What is worthy of obtaining the color attribute is the rgb color, which is not what we want, so we need to change the rgb color to hexadecimal color, and first obtain the rgb color:
The code copy is as follows:
var rgb = document.getElementById('color').style.backgroundColor;
The format is obtained as follows: rgb(225, 22, 23); and then split:
The code copy is as follows:
var rgb = rgb.split('(')[1]; //Array with length 2 after splitting
Then split the (225, 22, 23) string (note: only the number type can be converted, so use parseInt to cast the type!) :
The code copy is as follows:
for(var k = 0; k < 3; k++){
str[k] = parseInt(rgb .split(',')[k]).toString(16);//str array saves split data
}
The final combination:
The code copy is as follows:
str = '#'+str[0]+str[1]+str[2];
The entire code is as follows:
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<title>getHexColor js/jQuery Get hex 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="getbackground color" />
<input onclick="getHexColor();" type="button" value="get font color" />
</body>
</html>