在Javascript中将rgb字符串转换为十六进制 [英] Convert rgb strings to hex in Javascript

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

问题描述

我使用TweenMax JS库和ColorPropsPlugin,它可以调整以多种格式指定的颜色值,我遇到的问题是结果总是以字符串的形式显示:

I am using the TweenMax JS library with the ColorPropsPlugin which will tween color values which are specified in many formats, the problem I have is that the result is always in the form of a string:

"rgb(255,255,255)"

如何将它转换为十六进制数字:

How can that be converted in to a hex number like:

0xffffff


推荐答案

我会先剪掉CSS部分:

I would at first cut away the CSS parts:

var a = "rgb(255,255,255)".split("(")[1].split(")")[0];

然后将其分成不同的数字:

Then split it into separate numbers:

a = a.split(",");

将单个数字转换为十六进制

Convert the single numbers to hex

var b = a.map(function(x){             //For each array element
    x = parseInt(x).toString(16);      //Convert to a base16 string
    return (x.length==1) ? "0"+x : x;  //Add zero if we get only one character
})

然后粘贴到一起:

And glue it back together:

b = "0x"+b.join("");

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

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