在Javascript中如何在不指定rgb的情况下设置rgba?

saz*_*azr 26 html javascript css

我有一个HTML元素,其背景颜色设置为rgba()

<div style="background-color: rgba(2,100,100,0);"> </div>
Run Code Online (Sandbox Code Playgroud)

然后我有一个计时器,通过改变javascript中元素的不透明度值使背景慢慢淡入

myEle.style.backgroundColor = "rgba(x,x,x,0.1)"; // I have to know the rgb values to update the alpha value
Run Code Online (Sandbox Code Playgroud)

有没有办法在不更改/知道rgb值的情况下设置rgba()的值?

也许我可以做这样的事情?

var r = myEle.style.r;
var g = myEle.style.g;
var b = myEle.style.b;
myEle.style.backgroundColor = "rgba("+r+","+g+","+b+",0.1)";
Run Code Online (Sandbox Code Playgroud)

Rob*_*per 14

经过一些游戏,并发现了getComputedStyle,我把它放在了一起.

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      #element {
        background-color: rgb(10,10,10);
        background-color: rgba(10,10,10,1);
      }
    </style>
    <script type="text/javascript">      
      HTMLElement.prototype.alpha = function(a) {
        current_color = getComputedStyle(this).getPropertyValue("background-color");
        match = /rgba?\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*\d+[\.\d+]*)*\)/g.exec(current_color)
        a = a > 1 ? (a / 100) : a;
        this.style.backgroundColor = "rgba(" + [match[1],match[2],match[3],a].join(',') +")";
      }
    </script>
  </head>
  <body>
    <div id="element">
      This is some content.
    </div>
    <script type="text/javascript">
      e = document.getElementById('element');
      e.alpha(20);
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)
  • 确保在css中定义您的值,并级联,因为RGBA是CSS3.
  • 另外看到你可以为alpha传递一个> 1的数字,它将为你除以100(我讨厌在考虑百分比时使用小数).
  • 请享用!


Leo*_*nid 13

你有字符串,替换任何东西
'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')