Js to obtain the web page background color and font color method
- 2020-03-30 02:24:25
- OfStack
Get the background color and font color of the page by:
Thought: the RGB color is worth getting by getting the color attribute, not what we want, so we need to change the RGB color to hexadecimal color. First, we get the RGB color:
The format is as follows: RGB (225, 22, 23); Then split:
Split the (225,22,23) string (note: only number casts, so parseInt casts!) :
The final combination:
The entire code is as follows:
Thought: the RGB color is worth getting by getting the color attribute, not what we want, so we need to change the RGB color to hexadecimal color. First, we get the RGB color:
var rgb = document.getElementById('color').style.backgroundColor ;
The format is as follows: RGB (225, 22, 23); Then split:
var rgb = rgb.split('(')[1]; //Split into the form of [RGB, 225,22,23)], an array of length 2
Split the (225,22,23) string (note: only number casts, so parseInt casts!) :
for(var k = 0; k < 3; k++){
str[k] = parseInt(rgb .split(',')[k]).toString(16);//The STR array holds the split data
}
The final combination:
str = '#'+str[0]+str[1]+str[2];
The entire code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>getHexColor js/jQuery Gets 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 the background color " />
<input onclick="getHexColor();" type="button" value=" Get font color " />
</body>
</html>