I have an HTML element whose background colour is set with 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
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?
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)";
Changing the opacity of the background color only To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.
Each parameter (red, green, and blue) defines the intensity of the color between 0 and 255. For example, rgb(255, 0, 0) is displayed as red, because red is set to its highest value (255) and the others are set to 0. To display black, set all color parameters to 0, like this: rgb(0, 0, 0).
An RGB color value represents RED, GREEN, and BLUE light sources. An RGBA color value is an extension of RGB with an Alpha channel (opacity).
You got the string, replace whatever'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')
After some playing around, and the discovery of getComputedStyle, I have put together this.
<!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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With