Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  121] [ 1]  / answers: 1 / hits: 92386  / 13 Years ago, fri, november 18, 2011, 12:00:00

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);

More From » html

 Answers
8

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>



  • 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!


[#89049] Wednesday, November 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breanab

Total Points: 731
Total Questions: 95
Total Answers: 79

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;