HEX to RGB Converter

前端 未结 3 708
一整个雨季
一整个雨季 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:

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

    0 讨论(0)
  • 2021-01-19 20:17

    valid hex colors can have 3 or 6 characters after the '#'

    function hexToRgb(hex){
        if(/^#([a-f0-9]{3}){1,2}$/.test(hex)){
            if(hex.length== 4){
                hex= '#'+[hex[1], hex[1], hex[2], hex[2], hex[3], hex[3]].join('');
            }
            var c= '0x'+hex.substring(1);
            return 'rgb('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+')';
        }
    }
    
    0 讨论(0)
  • 2021-01-19 20:31

    You can pass the elementId to the function

    function hex2rgb( colour, id )
    ...
       $("#"+id).text("rgb(" + r + "," + g + "," + b + ")")
    }
    
    0 讨论(0)
提交回复
热议问题