将十六进制转换为 RGBA [英] Convert Hex to RGBA

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

问题描述

我的小提琴 - 是一个很棒的颜色处理 js 库,它可以满足我的所有需求以及更多功能.我想你们可能想试一试!- https://github.com/bgrins/TinyColor

解决方案

//如果你自己写代码,记住十六进制颜色快捷键(例如,#fff、#000)函数 hexToRgbA(hex){变量 c;if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){c= hex.substring(1).split('');if(c.length== 3){c= [c[0], c[0], c[1], c[1], c[2], c[2]];}c='0x'+c.join('');return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';}throw new Error('Bad Hex');}hexToRgbA('#fbafff')/* 返回值:(字符串)RGBA(251,175,255,1)*/

My fiddle - http://jsbin.com/pitu/1/edit

I wanted to try an easy hex to rgba conversion. Ever browser I've used renders colors using rgb as default so when using the farbtastic color picker I'm converting the hex value to rgb by grabbing the background color the hex value generates (as rgb by default = simple conversion)

I tried replacing the ) symbol to , 1), but that didn't work so I went to just see how converting rgb to rgba would work, and I'm still having trouble.

The jquery

$('.torgb').val($('#color').css('background-color'));
$('.torgba').val().replace(/rgb/g,"rgba");

The goal

EDIT:

TinyColor Is a great color manipulation js library that does everything I want here and more. I figure you guys may want to give it a try! - https://github.com/bgrins/TinyColor

解决方案

//If you write your own code, remember hex color shortcuts (eg., #fff, #000)

function hexToRgbA(hex){
    var c;
    if(/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)){
        c= hex.substring(1).split('');
        if(c.length== 3){
            c= [c[0], c[0], c[1], c[1], c[2], c[2]];
        }
        c= '0x'+c.join('');
        return 'rgba('+[(c>>16)&255, (c>>8)&255, c&255].join(',')+',1)';
    }
    throw new Error('Bad Hex');
}

hexToRgbA('#fbafff')

/*  returned value: (String)
rgba(251,175,255,1)
*/

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

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