HEX to RGB Converter

前端 未结 3 739
一整个雨季
一整个雨季 2021-01-19 19:43

I have the JavaScript for converting a HEX value to RGB but I was wondering if I could use jQuery to call the function and insert the HTML?

Here\'s the JavaScript;

3条回答
  •  梦谈多话
    2021-01-19 20:16

    HTML:

    
    
    
    ​​​​​​​​​​​​

    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/

提交回复
热议问题