【问题标题】:HEX to RGB Converter十六进制到 RGB 转换器
【发布时间】:2012-10-08 06:27:35
【问题描述】:

我有用于将 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 + “)”;
}

更新

我正在尝试使用它,因此有一个输入字段,您可以在其中输入十六进制值,按回车键,然后插入 RGB 值(可能在幻影元素或其他东西中)。

【问题讨论】:

  • 可能需要更多关于您具体尝试做什么的信息。
  • jQuery JavaScript 所以是的。
  • 你在想:十六进制值进入文本输入 -> 按钮 -> 将 rgb 输出为文本?

标签: javascript jquery html


【解决方案1】:

有效的十六进制颜色在“#”之后可以有 3 个 6 个字符

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(',')+')';
    }
}

【讨论】:

    【解决方案2】:

    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/

    【讨论】:

    【解决方案3】:

    你可以将 elementId 传递给函数

    function hex2rgb( colour, id )
    ...
       $("#"+id).text("rgb(" + r + "," + g + "," + b + ")")
    }
    

    【讨论】:

    • 您有示例/演示吗?我是 JS 新手,这很令人困惑。
    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 2021-03-22
    • 2021-11-09
    • 2013-03-19
    • 2020-11-14
    相关资源
    最近更新 更多