Home > Web Front-end > JS Tutorial > body text

Javascript realizes Web color value conversion_javascript skills

WBOY
Release: 2016-05-16 16:15:34
Original
1080 people have browsed it

I have been busy completing business needs recently and haven’t blogged for a long time. I had a little time today and looked through some front-end codes in recent projects. When I saw the Web color conversion function, it suddenly occurred to me that when we do some color setting/editing requirements, we often involve various color value formats. of exchange. So I decided to record how I implemented this part of the function, write it down and share it with everyone. I hope readers can express their opinions and communicate more.

Look at the problem first

Question 1. When we are doing web front-end development, we often use dom.style.backgroundColor = "#f00" to set the background color of a certain DOM element. We also use similar (why similar? Situation comparison (More, you can use your imagination freely here) var bgc = dom.style.backgroundColor code to get the background color of a certain DOM element. So here comes the question, please look at the picture below:

If the contrast here is not obvious enough, let’s continue reading:

Obviously, the same color value should be equal, but the result is not. And this is not an isolated case. The results obtained by the author in Chrome development tools and Firefox console are consistent.

Question 2: Front-end development work often starts with restoring the UI design draft. During the coding process, we often find designs like this: a box background has a solid color (say: #f00), but with an opacity of 75%. Obviously, in this case we cannot simply set it through dom.style.backgroundColor = "#f00" because the translucent effect cannot be achieved. Turning the topic around, we know that there is an rgba thing in CSS3, which means that we can set a translucent background color through dom.style.backgroundColor = "rgba(255, 0, 0, 0.75)". So, here comes the question again: This conversion is easy to do in Photoshop, but in Javascript, how do we convert ("#f00", 75) into rgba(255, 0, 0, 0.75)? ?

Next, let’s see how I did it.

Convert rgb(a) color value to hexadecimal color (hex)

They are all developers, we understand! It’s better to write code directly than anything else, but here’s the most original one:

Copy code The code is 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 it said to be the most original? Because when I reviewed the code today, I found that there is still room for evolution. Next, let’s compare the evolved (optimized) code:

Copy code The code is 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};
}
};

Not to mention the missing if branch, it is obvious just from the amount of code! Next, let’s see if the result of the conversion is as we expected. To do this, I executed the following lines of code in the console:

Judging from the execution results, our method seems to have achieved our purpose. However, attentive friends should have noticed that there are two red arrows in the picture. Is there any pitfall here? good. Let's take a closer look at the color parameter rgb(255, 0, 0, 2) passed in the first arrow. In fact, this is not a legal color value. The color value in rgb format does not have the fourth (transparency) parameter. ; look at rgba(255, 0, 0, 1.48) in the second arrow. The format here is OK, but the transparency is 1.48, which is not a legal transparency value. In both cases, our method was executed normally and returned normally. This shows that our method still has room for further evolution, and we will leave it to everyone to use it!

Convert hexadecimal color (hex) to rgba format

In daily development, the color values ​​we most commonly use should be the color values ​​in hexadecimal format (#ff0000, #f00, etc.). If we need to convert the color values ​​to rgba format when using them, we What to do?

Copy code The code is 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) ')'
};
};

Similarly, we also write a verification code to test whether our conversion is normal:

Judging from the execution results, there is no problem with our method and we can get the conversion results we want. But here we are still left with two red arrows, illegal transparency and illegal color value. This part of the evolution function is also left to everyone, haha...

Finally, the mutual conversion between web page color values ​​is actually a commonplace problem. I have simply listed one here. I believe there are more and better methods that can be used. Everyone is welcome to propose. Let’s communicate and make progress together~~

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!