Javascript 在Javascript中如何设置rgba而不指定rgb?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8177964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:59:13  来源:igfitidea点击:

In Javascript how can I set rgba without specifying the rgb?

javascripthtmlcss

提问by sazr

I have an HTML element whose background colour is set with rgba()

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

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

Then I have a timer that makes the background slowly fade in by changing the opacity value of the element in javascript

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

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

Is there a way to set the a value of rgba() without changing/knowing the rgb values?

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

Maybe I can do something like this?

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

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

采纳答案by Rob Cooper

After some playing around, and the discovery of getComputedStyle, I have put together this.

经过一些玩耍和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>
  • Make sure you define in your css your values, and cascade because RGBA is CSS3.
  • Also see that you can pass in a number >1 for alpha and it will divide by 100 for you (I hate working with decimals when thinking percentages).
  • Enjoy!
  • 确保你在你的 css 中定义了你的值,并且因为 RGBA 是 CSS3 级联。
  • 另请参阅您可以为 alpha 传递一个 >1 的数字,它将为您除以 100(我讨厌在考虑百分比时使用小数)。
  • 享受!

回答by Leonid

You got the string, replace whatever
'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')

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

回答by rekire

You could also use elem.style.opacity=0.5or in html style="opacity:0.5". It is important to note that the child nodes will fade too.

您也可以elem.style.opacity=0.5在 html 中使用或style="opacity:0.5"。重要的是要注意子节点也会消失。

回答by Jonathon

I had do this too but ended up writing something a little more specific. I put it in a jQuery plugin that accepts a min and max opacity:

我也这样做过,但最终写了一些更具体的东西。我把它放在一个接受最小和最大不透明度的 jQuery 插件中:

$.fn.setAlpha = function ( options ) {
    var settings = $.extend({
        alpha: 0.5,
        min: 0,
        max: 1
    }, options );
    return this.each(function() {
        var color = $(this).css('background-color');
        if (color.substring(0,4) === 'rgba') {
            var a;
            if (settings.alpha <= settings.min) {
                a = settings.min;
            } else if (settings.alpha >= settings.max) {
                a = settings.max;
            } else {
                a = settings.alpha;
            }
            var rgba = color.replace(/[^,]+(?=\))/, a);
            $(this).css('background-color', rgba);
        }
    });
}

$.fn.getAlpha = function () {

    var color = this.css('background-color');
    if (color.substring(0,4) === 'rgba') {
        var alpha = color.split(',');
            alpha = alpha[alpha.length - 1].trim();
            alpha = alpha.substring(0, alpha.indexOf(")"));
        return alpha;
    } else {
        return 1;
    }
}

then you use them to do something like this to set a div to transparent and fade it to its original opacity as you scroll down:

然后你使用它们来做这样的事情来将一个 div 设置为透明,并在向下滚动时将其淡化为原始不透明度:

//get original opacity
var originalOpacity = $('#myDiv').getAlpha(); 

//set new opacity
//it will be 0 at the top of the page
var newOpacity = $(window).scrollTop()/500;
$('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity}); 

//on scroll fade new opacity to originalOpacity at 500px down
$(window).scroll( function() {
     var newOpacity = $(window).scrollTop()/500;
     $('#myDiv').setAlpha({"alpha": newOpacity, "max": originalOpacity});
}

回答by r0ast3d