我有一个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()的值?
也许我可以做这样的事情?
var r = myEle.style.r;
var g = myEle.style.g;
var b = myEle.style.b;
myEle.style.backgroundColor = "rgba("+r+","+g+","+b+",0.1)";
答案 0 :(得分: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>
答案 1 :(得分:11)
你得到了字符串,替换了什么
'rgba(1,1,1,0.3)'.replace(/[^,]+(?=\))/, '0.5')
答案 2 :(得分:1)
您也可以使用elem.style.opacity=0.5
或html style="opacity:0.5"
。值得注意的是,子节点也会褪色。
答案 3 :(得分:1)
我也是这样做的,但结果写了一些更具体的东西。我把它放在一个接受最小和最大不透明度的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;
}
}
然后你用它们来做这样的事情来将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});
}
答案 4 :(得分:0)