2010-06-15 44 views
16

Trong file CSS của tôi:Giá trị màu jquery css trả về RGB?

a, a:link, a:visited { color:#4188FB; } 
a:active, a:focus, a:hover { color:#FFCC00; } 

Tôi đã thử với:

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

Làm thế nào tôi có thể lấy mã HEX?

*** sửa: tìm thấy câu trả lời ở đây:
Background-color hex to JavaScript variable

Xấu hổ về tôi, có thể có tìm kiếm một chút tốt hơn trước khi gửi bài ..

+0

http://stackoverflow.com/questions/1740700/jquery-get-hex-value-rather-rgb – user113716

+0

thể trùng lặp của [background-color hex để biến JavaScript (jQuery) ] (http://stackoverflow.com/questions/638948/background-color-hex-to-javascript-variable-jquery) – zzzzBov

Trả lời

4

Ở đây bạn đi, điều này sẽ cho phép bạn sử dụng $ (selector) .getHexBackgroundColor() để trả về giá trị hex dễ dàng:

$.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

không thành công trong ie8, xem http://stackoverflow.com/a/7380712/21460 –

8

Một số adjustes hoạt

$.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

Đây là của tôi. Đơn giản và súc tích.

(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>

Các vấn đề liên quan