2010-06-15 2 views
16

:jquery css color 값이 RGB를 반환합니까? 내 CSS 파일에서

내가 함께 노력
a, a:link, a:visited { color:#4188FB; } 
a:active, a:focus, a:hover { color:#FFCC00; } 

:

var link_col = $("a:link").css("color"); 
alert(link_col); // returns rgb(65, 136, 251) 

가 어떻게 16 진수 코드를받을 수 있나요?

*** 편집 :
Background-color hex to JavaScript variable

나 부끄러운, 게시하기 전에 조금 더 나은 검색 할 수 ..

당신이 가서 여기
+0

http://stackoverflow.com/questions/1740700/jquery-get-hex-value-rather-rgb 스크립트 변수 [배경색 헥스 – user113716

+0

중복 가능성 (jQuery를) ] (http://stackoverflow.com/questions/638948/background-color-hex-to-javascript-variable-jquery) – zzzzBov

답변

4

,이 사용할 수 있습니다 : 여기에 대한 답을 발견 $ (선택) .getHexBackgroundColor()는 쉽게 16 진수 값을 반환 :

$.fn.getHexBackgroundColor = function() { 
    var rgb = $(this).css('background-color'); 
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); 
    function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);} 
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
} 
+1

ie8에서 실패합니다. http://stackoverflow.com/a/7380712/21460을 참조하십시오. –

8

일부 adjustes이

를 작동하기
$.fn.getHexBackgroundColor = function() { 
    var rgb = $(this).css('background-color'); 
    if (!rgb) { 
     return '#FFFFFF'; //default color 
    } 
    var hex_rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); 
    function hex(x) {return ("0" + parseInt(x).toString(16)).slice(-2);} 
    if (hex_rgb) { 
     return "#" + hex(hex_rgb[1]) + hex(hex_rgb[2]) + hex(hex_rgb[3]); 
    } else { 
     return rgb; //ie8 returns background-color in hex format then it will make     compatible, you can improve it checking if format is in hexadecimal 
    } 
} 
0

여기 내 걸립니다. 간단하고 간결합니다.

(function($) { 
 
    $.fn.getHexBackgroundColor = function() { 
 
    return (function(rgb) { 
 
     return '#' + (!rgb 
 
     ? 'FFFFFF' 
 
     : rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/) 
 
      .slice(1) 
 
      .map(x => ('0' + parseInt(x).toString(16)).slice(-2)) 
 
      .join('') 
 
      .toUpperCase()); 
 
    })($(this).css('background-color')); 
 
    } 
 
})(jQuery); 
 

 
$(function() { 
 
    $('#color-rgb').text($('.foo').css('background-color')); 
 
    $('#color-hex').text($('.foo').getHexBackgroundColor()); 
 
});
.foo { 
 
    background: #F74; 
 
    width: 100px; 
 
    height: 100px; 
 
} 
 

 
label { font-weight: bold; } 
 
label:after { content: ': '; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="foo"></div> 
 
<label>RGB</label><span id="color-rgb">UNDEF</span><br /> 
 
<label>HEX</label><span id="color-hex">UNDEF</span>