为什么透明度 rgba 只在第一次工作

Why transparency rgba works only first time

透明度应该随rgba改变,但rgb不应该改变。只有 "a" 应该可以更改。它只在第一次有效,如果我想第二次更改该值为 null。我哪里错了?

<select id="elementbackgroundtransparency" onchange="ElementBackgroundTransparency()">
    <option value="1">1</option>                 
    <option value="0.1">0.1</option>                 
    <option value="0.2">0.2</option>                
    <option value="0.3">0.3</option>                 
    <option value="0.4">0.4</option>                 
    <option value="0.5">0.5</option>                 
    <option value="0.6">0.6</option>
    <option value="0.7">0.7</option>
    <option value="0.8">0.8</option>
    <option value="0.9">0.9</option>
</select>

<div id="color" style="height:50px;width:50px;background-color:rgba(255,0,0,0.3);"></div>
function ElementBackgroundTransparency(){
        var t = document.getElementById("elementbackgroundtransparency").value;
        var elem = document.getElementById("color");
        var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");

        var rgb = /rgb\((\d+), (\d+), (\d+)\)/.exec(theCSSprop);
        var r = rgb[1];
        var g = rgb[2];
        var b = rgb[3];
        document.getElementById("color").style.backgroundColor = "rgba("+r+", "+g+", "+b+""+", "+t+")";

}

可能是您的 RGB 索引不是从 0 开始的

由于 ARGBA 1[=31 中的值,您的函数第一次运行良好=] 这等于什么都没有,因此你的

var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");

return rgba(255, 0, 0) 这是 regex

的正确值

但是当您从下拉菜单中更改选项时,您的脚本 return rgba(255, 0, 0,0.3) 您的输入错误正则表达式 表达式。

您必须在传递给正则表达式之前纠正 theCSSprop 值。

function ElementBackgroundTransparency(){
        var t = document.getElementById("elementbackgroundtransparency").value;
        var elem = document.getElementById("color");
        var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
        theCSSprop = theCSSprop.split(",");
        if(theCSSprop.length > 3){
            theCSSprop[0] = theCSSprop[0].replace("a","");
            theCSSprop.splice(-1, 1);
            theCSSprop = theCSSprop.join(",");
            theCSSprop += ")";
        }
        console.log(theCSSprop);
        var rgb = /rgb\((\d+), (\d+), (\d+)\)/.exec(theCSSprop);
        if(rgb !== null){
            var r = rgb[1];
            var g = rgb[2];
            var b = rgb[3];
            document.getElementById("color").style.backgroundColor = "rgba("+r+", "+g+", "+b+""+", "+t+")";
        }else{
            console.log(rgb,"failed");
        }
}

jsFiddle link