요소의 배경색 코드를 얻는 방법은 무엇입니까?
요소의 배경색 코드는 어떻게 얻습니까?
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).css("background-color");
결과
rgb(245, 180, 5)
내가 원하는 것
#f5b405
아래 예제 링크를 확인하고 div를 클릭하여 16 진수 색상 값을 가져옵니다.
var color = '';
$('div').click(function() {
var x = $(this).css('backgroundColor');
hexc(x);
alert(color);
})
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
http://jsfiddle.net/DCaQb/ 에서 작동 예를 확인하십시오.
특정 속성이 다음 strokeStyle
과 fillStyle
같이 설정 될 때 HTML5 캔버스가 색상 값을 구문 분석해야하기 때문에 약간의 해킹이 있습니다 .
var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;
function getBackgroundColor($dom) {
var bgColor = "";
while ($dom[0].tagName.toLowerCase() != "html") {
bgColor = $dom.css("background-color");
if (bgColor != "rgba(0, 0, 0, 0)" && bgColor != "transparent") {
break;
}
$dom = $dom.parent();
}
return bgColor;
}
Chrome 및 Firefox에서 제대로 작동
원하는 형식으로 변환하는 데 필요한 색상이 있습니다.
다음은 트릭을 수행해야하는 스크립트입니다. http://www.phpied.com/rgb-color-parser-in-javascript/
실제로, 어떠한 정의가 존재하지 않는 경우 background-color
그 어떤 소자, 크롬가 출력 하에서 background-color
같은 rgba(0, 0, 0, 0)
반면, 파이어 폭스 출력은이다 transparent
.
My beautiful non-standard solution
HTML
<div style="background-color:#f5b405"></div>
jQuery
$(this).attr("style").replace("background-color:", "");
Result
#f5b405
Adding on @Newred solution. If your style has more than just the background-color
you can use this:
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1]
This Solution utilizes part of what @Newred and @Radu Diță said. But will work in less standard cases.
$(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');
The issue both of them have is that neither check for a space between background-color: and the color.
All of these will match with the above code.
background-color: #ffffff
background-color: #fffff;
background-color:#fffff;
참고URL : https://stackoverflow.com/questions/5999209/how-to-get-the-background-color-code-of-an-element
'Program Tip' 카테고리의 다른 글
"무한"반복자가 잘못된 설계입니까? (0) | 2020.11.14 |
---|---|
내부 클래스에서 외부 클래스의 "this"에 어떻게 액세스 할 수 있습니까? (0) | 2020.11.14 |
문자열 비교 자바 스크립트 반환 가능성 % (0) | 2020.11.14 |
Runnable의 run () 예외를 발생시키는 방법이 있습니까? (0) | 2020.11.14 |
문자열이 같지 않은 경우 어떻게 비교합니까? (0) | 2020.11.14 |