在字符串中将RGB转换为0.9 alpha的RGBA



我需要采用颜色渐变,将rgb动态更改为rgba,并添加0.9 alpha或其他数字。当然div id=";梯度";可以有三种以上的rgb和rgba颜色。我尝试替换(('(',',0.9('(。替换('rgb','rgba'(;但它不起作用。我该怎么做?

结果应该是:

线性梯度(90度,rgba(205,55,55,0.7(11%,rgba(80,55,205,0.9(45%,rgba

function myFunction() {
var gradient = document.getElementById("gradient").style.background;
document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}
<div id="gradient" style="background: linear-gradient(
90deg
, rgba(215, 45, 45, 0.7) 11%, rgb(73, 45, 215) 45%, rgba(45, 215, 65, 0.5) 79%);"></div>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>

要在样式中直接替换,可以使用下面的代码。但是,如果可能的话,您应该在css文件中拥有不同的样式,然后只需在单击时切换整个元素样式(例如gradient-idlegradient-clicked或任何您需要的样式(。

function myFunction() {
var gradient = document.getElementById("gradient")
.style
.background
.replace(/rgb([0-9]{1,3},s[0-9]{1,3},s[0-9]{1,3}/, "$&, 0.75") // put another alpha here instead of 0.75
.replace("rgb(", "rgba("); // then replace rgb( with rgba(
document.getElementById("demo").innerHTML = gradient;
document.getElementById("demo").style.background = gradient;
}
<div id="gradient" style="
background: linear-gradient(90deg,
rgba(205, 55, 55, 0.7) 11%,
rgb(80, 55, 205) 45%,
rgba(55, 205, 73, 0.5) 79%);"></div>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>

也可以是:

// a regular expression with named capturing group "rgb" that captures the RGB values: "rgb(1, 20, 140)" -> "1, 20, 140"
const r = /rgb((?<rgb>d+s*,s*d+s*,s*d+))/;
let style = 'linear-gradient(90deg, rgb(205, 55, 55) 11%, rgb(80, 55, 205) 45%, rgb(55, 205, 73) 79%)';
// now we can change the values 1 by 1
style = style.replace(r, "rgba($1, 0.7)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgb(80, 55, 205) 45%, rgb(55, 205, 73) 79%)
style = style.replace(r, "rgba($1, 0.9)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgb(55, 205, 73) 79%)
style = style.replace(r, "rgba($1, 0.5)");
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)
console.log(style);
// linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

相关内容

  • 没有找到相关文章

最新更新