웹 페이지의 배경색 및 글꼴 색상을 얻으려면이 메소드는 다음과 같습니다.
생각 : 색상 속성을 얻을 가치가있는 것은 RGB 색상입니다. RGB 색상은 우리가 원하는 것이 아니므로 RGB 색상을 16 진 색상으로 변경하고 먼저 RGB 색상을 얻어야합니다.
코드 사본은 다음과 같습니다.
var rgb = document.getElementById ( 'color'). Style.backgroundColor;
형식은 다음과 같이 얻어진다 : RGB (225, 22, 23);
코드 사본은 다음과 같습니다.
var rgb = rgb.split ( '(') [1]; 분할 후 길이 2가있는 배열
그런 다음 (225, 22, 23) 문자열을 분할하십시오 (참고 : 숫자 유형 만 변환 할 수 있으므로 Parseint를 사용하여 유형을 캐스트하십시오!) :
코드 사본은 다음과 같습니다.
for (var k = 0; k <3; k ++) {
str [k] = parseint (rgb .split ( ',') [k]). tostring (16); // str array는 분할 데이터를 저장합니다
}
최종 조합 :
코드 사본은 다음과 같습니다.
str = '#'+str [0]+str [1]+str [2];
전체 코드는 다음과 같습니다.
코드 사본은 다음과 같습니다.
<! doctype html>
<html>
<헤드>
<title> gethexcolor js/jQuery hex hex color </title>
<meta charset = "utf-8" />
<script type = "text/javaScript">
함수 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;
}
함수 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;
}
</스크립트>
<스타일 유형 = "텍스트/CSS">
#색상{
너비 : 200px;
높이 : 200px;
라인 높이 : 200px;
텍스트 정렬 : 센터;
}
</스타일>
</head>
<body>
<div style = "색상 : #88ee22; 배경색 : #ef8989;"
<input onclick = "gethexbgcolor ();"value = "getbackground color" />
<input onclick = "gethexcolor ();"value = "font color get" />
</body>
</html>