


How to get the background color and font color of the web page in js_javascript skills
May 16, 2016 pm 04:54 PMTo get the background color and font color of the web page, the method is as follows:
Thought: What we get by getting the color attribute value is RGB color, which is not what we want, so we need to change the RGB color to hexadecimal color , first 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]; //After splitting, it is [rgb, 225 ,22,23)] form, an array of length 2
and then split the (225,22,23) string (note: only number type can be converted, so use parseInt to force Conversion type! ):
for(var k = 0; k < 3; k ){
str[k] = parseInt(rgb .split(',')[k]).toString(16);//str array saves the split data
}
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 the font color" />
</body>
</html>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to send web pages to desktop as shortcut in Edge browser?

How to change the background color of Google Chrome? How to set the background color of Google Chrome

Develop web voting system using JavaScript

What to do if the web page cannot be accessed

Possible reasons why the network connection is normal but the browser cannot access the web page

How to set up web page automatic refresh

What to do if the webpage cannot be opened

What should I do if the images on the webpage cannot be loaded? 6 solutions
