十六进制到RGB转换器 [英] HEX to RGB Converter

查看:116
本文介绍了十六进制到RGB转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这是JavaScript;

Here's the 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值(也许在ghost元素中).

Update

I'm trying to have it so there is one input field where you type in a hex value, hit enter, and then the RGB value is inserted (maybe in a ghost element or something).

推荐答案

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/

这篇关于十六进制到RGB转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆