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

新手上路,请多包涵

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

<div style="background-color: rgba(2,100,100,0);"> </div>

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

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

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

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

 var r = myEle.style.r;
var g = myEle.style.g;
var b = myEle.style.b;
myEle.style.backgroundColor = "rgba("+r+","+g+","+b+",0.1)";

原文由 sazr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 303
2 个回答

经过一番尝试,发现了 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>

  • 确保在你的 css 中定义你的值,并级联,因为 RGBA 是 CSS3。
  • 另请注意,您可以为 alpha 传递一个大于 1 的数字,它会为您除以 100(我讨厌在考虑百分比时使用小数)。
  • 享受!

原文由 Rob Cooper 发布,翻译遵循 CC BY-SA 3.0 许可协议

你得到了字符串,替换任何东西

var oldCss = 'rgba(1,1,1,0.3)',
newOpacity = '0.5',
newCss = oldCss.replace(/[^,]+(?=\))/, newOpacity);

console.log(oldCss, "replaced with", newCss);

原文由 Leonid 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题