javascript – HEX到RGB转换器

我有用于将HEX值转换为RGB的
JavaScript,但我想知道是否可以使用jQuery来调用函数并插入HTML?

这是JavaScript;

function hex2rgb( colour ) {
    var r,g,b;
      if ( colour.charAt(0) == ‘#’ ) {
          colour = colour.substr(1);
    }

    r = colour.charAt(0) + ” + colour.charAt(1);
    g = colour.charAt(2) + ” + colour.charAt(3);
    b = colour.charAt(4) + ” + colour.charAt(5);

    r = parseInt( r,16 );
    g = parseInt( g,16 );
    b = parseInt( b ,16);
    return “rgb(” + r + “,” + g + “,” + b + “)”;
}

更新

我想要它,所以有一个输入字段,你键入十六进制值,按Enter键,然后插入RGB值(可能在鬼元素或其他东西).

最佳答案 HTML:

<input type="text" id="hex-input" placeholder="hex goes here"/>
<button id="magic-button">PUSH ME!</button>
<div id="rgb-output"></div>​​​​​​​​​​​​

JS:

$(document).ready(function() {
    $("#magic-button").click(function() {
        $("#rgb-output").html(hex2rgb($("#hex-input").val()));
    });

    $("#hex-input").keyup(function(event){
        if(event.keyCode == 13){
            $("#magic-button").click();
        }
    });
});

function hex2rgb( colour ) {
    var r,g,b;
    if ( colour.charAt(0) == '#' ) {
        colour = colour.substr(1);
    }
    if ( colour.length == 3 ) {
        colour = colour.substr(0,1) + colour.substr(0,1) + colour.substr(1,2) + colour.substr(1,2) + colour.substr(2,3) + colour.substr(2,3);
    }
    r = colour.charAt(0) + '' + colour.charAt(1);
    g = colour.charAt(2) + '' + colour.charAt(3);
    b = colour.charAt(4) + '' + colour.charAt(5);
    r = parseInt( r,16 );
    g = parseInt( g,16 );
    b = parseInt( b ,16);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}​    

http://jsfiddle.net/2fb3D/

点赞