JavaScript implements web color value conversion _javascript Tips

Source: Internet
Author: User

have been busy recently to complete the business needs, for a long time did not write a blog. Today for a little while, looking at some of the recent project's front-end code, see the Web color conversion function, suddenly think of when we do some color settings/editing requirements, often involves a variety of color value format interchange. So I decided to record what I do in this part of the time is how to achieve, write down and share with you, I hope that readers to express their views, a lot of exchanges.

Look at the problem first.

Problem one, when we are in the front-end development of the Web page, often use Dom.style.backgroundColor = "#f00" to set the background color of a DOM element, also through the similar (why is similar?) The situation is more, here is free to play the imagination) var BGC = Dom.style.backgroundColor code to get the background color of a DOM element. So here's the question, look at the picture below:

If the contrast here is not clear enough, let's continue to look at it:

Obviously, the same color value should have been equal, but the result is not the case. This is not the case, the author in the Chrome development tools and Firefox console, the results are consistent.

Problem two, front-end development work, often starting from the restore UI design. And in the coding process we often find this design: A box background solid color (assuming: #f00), but with 75% opacity. Obviously, this situation cannot be set simply by Dom.style.backgroundColor = "#f00" because the translucent effect is not achieved. Changed, we know that there is a rgba in CSS3, which means that we can set the background color with semitransparent by Dom.style.backgroundColor = "Rgba (255, 0, 0, 0.75)". So, here's the problem: This conversion is easy to do in Photoshop, but how do we convert ("#f00", 75) to Rgba (255, 0, 0, 0.75) in JavaScript?

Next, let's take a look at how I did it.

RGB (a) color values are converted to hexadecimal color (hex)

Are doing development, we understand! It's better to say nothing than to get the code straight, but let's put a piece of the original:

<!--Lang:js-->

Copy Code code as follows:

var Rgbtohex = function (RGB) {
var Rrgb =/rgb\ ((\d{1,3}), (\d{1,3}), (\d{1,3}) \)/,
Rrgba =/rgba\ (\d{1,3}), (\d{1,3}), (\d{1,3}), ([. \d]+) \)/,
R, G, B, a, rs = Rgb.replace (/\s+/g, ""). Match (RRGB),
RSA = Rgb.replace (/\s+/g, ""). Match (Rrgba);
if (RS) {
r = (+rs[1]). toString (16);
r = R.length = 1? "0" + r:r;
g = (+rs[2]). toString (16);
G = G.length = = 1? "0" + g:g;
b = (+rs[3]). toString (16);
b = b.length = 1? "0" + b:b;
return {hex: "#" + r + G + B, alpha:100};
else if (RSA) {
r = (+rsa[1]). toString (16);
r = R.length = 1? "0" + r:r;
g = (+rsa[2]). toString (16);
G = G.length = = 1? "0" + g:g;
b = (+rsa[3]). toString (16);
b = b.length = 1? "0" + b:b;
A = (+rsa[4]) * 100
return {hex: "#" + r + G + B, Alpha:Math.ceil (a)};
} else {
return {HEX:RGB, alpha:100};
}
};

Why is that the most original? Because when I review the code today, I found there was room for evolution, and then I compared the evolutionary (optimized) code:

<!--Lang:js-->

Copy Code code as follows:

var Rgbtohex = function (RGB) {
var Rrgba =/rgba?\ ((\d{1,3}), (\d{1,3}), (\d{1,3}) (, ([. \d]+))? \)/,
R, G, B, A,
RSA = Rgb.replace (/\s+/g, ""). Match (Rrgba);
if (RSA) {
r = (+rsa[1]). toString (16);
r = R.length = 1? "0" + r:r;
g = (+rsa[2]). toString (16);
G = G.length = = 1? "0" + g:g;
b = (+rsa[3]). toString (16);
b = b.length = 1? "0" + b:b;
A = (+ (rsa[5]? Rsa[5]: 1) * 100
return {hex: "#" + r + G + B, Alpha:Math.ceil (a)};
} else {
return {HEX:RGB, alpha:100};
}
};

And do not say less than an if branch, the single from the amount of code to see, it is obvious! Next, let's see if the result of the conversion is as we would like it to be, so I executed a few lines of code in the console as shown in the following illustration:

From the results of the implementation, our approach seems to have been able to achieve our goal. However, careful friends should notice that there are two red arrows in the picture, is there any pit here? Not bad. Let's take a closer look at the first arrow, the color parameter passed in RGB (255, 0, 0, 2), in fact, here is not a valid color value, RGB format color value, there is no fourth (transparency) parameter; Look at the second arrow rgba (255, 0, 0, 1.48), There is no problem with the format, but the transparency is 1.48, but it's not a legitimate transparency value. Both of these cases, our methods are normal implementation, but also normal return, that we have the method of further evolution of space, to give everyone their own play!

hexadecimal color (hex) into RGBA format

In our daily development, the color values we use most often should be the hexadecimal format color values (#ff0000, #f00等), what should we do if we need to convert to RGBA format when we use color values?

<!--Lang:js-->

Copy Code code as follows:

var Hextorgba = function (Hex, AL) {
var hexcolor =/^#/.test (hex)? Hex.slice (1): Hex,
ALP = Hex = = ' Transparent '? 0:math.ceil (AL),
R, G, B;
Hexcolor =/^[0-9a-f]{3}| [0-9a-f] {6}$/i.test (hexcolor)? Hexcolor: ' Fffff ';
if (hexcolor.length = = 3) {
Hexcolor = Hexcolor.replace (\w) (\w) (\w)/gi, ' $1$1$2$2$3$3 ');
}
r = Hexcolor.slice (0, 2);
g = Hexcolor.slice (2, 4);
b = Hexcolor.slice (4, 6);
R = parseint (r, 16);
g = parseint (g, 16);
b = parseint (b, 16);
return {
Hex: ' # ' + Hexcolor,
Alpha:alp,
RGBA: ' Rgba (' + R + ', ' + G + ', ' + B + ', ' + (alp/100). toFixed (2) + ') '
};
};

Also, we write a validation code to test whether our conversion is normal:

From the results of the implementation, our approach, no problem, can get the conversion results we want. But it still leaves everyone with two red arrows, illegal transparency and illegal color values. This part of the evolution of the function also left to everyone, haha ...

Finally, the page color value of the conversion between, in fact, is a cliché of the problem, I am here is simply listed a kind, I believe there are more and better ways to use, welcome everyone to put forward, we exchange, common progress ~ ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.