简体   繁体   English

从 JavaScript 中的 CSS 颜色模式字符串更改多个实体的 alpha 通道值

[英]Change the alpha channel values for multiple entities from a CSS color pattern string in JavaScript

Suppose we have this constant representing a CSS color pattern:假设我们有这个常数代表 CSS 颜色模式:

const COLOR = 'rgba(100,100,200, 0) rgb(100, 100, 200) rgba(100,200,250) rgba(100,200,250,0.8) rgba(40, 50, 60, 1)';

What would be the fastest method (match/regexp...?) in JavaScript to add 0.1 to the alpha channel of each rgba(...) and if it is rgb(...), to change it to rgba(...) with the alpha channel (ie: 0.1)? JavaScript 中最快的方法(匹配/正则表达式...?)将 0.1 添加到每个 rgba(...)的 alpha 通道,如果它是 rgb(...),将其更改为 rgba(。 ..) 带有 alpha 通道(即:0.1)? If a rgba(...) already has an alpha channel of 1, it should stay at 1, even though a higher value would not break anything to the computed style.如果 rgba(...) 已经有一个 1 的 alpha 通道,它应该保持为 1,即使更高的值不会破坏计算样式的任何内容。

So the resulting string would be:所以结果字符串将是:

rgba(100,100,200, 0.1) rgba(100, 100, 200, 0.1) rgba(100,200,250,0.1) rgba(100,200,250,0.9) rgba(40, 50, 60, 1)

Your first step is to replace rgb with rgba, then add 0.1 to the last number is it's less than 1 and finally replace instances where you only have three values to four (this regex looks weird because some of your parenthesised numbers have spaces and others don't)您的第一步是将 rgb 替换为 rgba,然后将 0.1 添加到最后一个数字是否小于 1,最后将只有三个值的实例替换为四个(这个正则表达式看起来很奇怪,因为您的一些带括号的数字有空格而其他数字没有't)

COLOR.replace(/rgb\(/g, 'rgba(').replace(/(\d\.\d|[^\d]0)\)/g, (match, p1) => {return String(Number(p1)+0.1) + ')';}).replace(/(\( *\d+ *, *\d+ *, *\d+ *)(\))/g, '$1,0.1$2')

It's important to note this will only work if your third value is ALWAYS bigger than 1.请务必注意,这仅在您的第三个值始终大于 1 时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM