问题描述
我只想更改现有背景色的不透明度,该颜色由服务器控制,我无法更改它,因为我使用的是网站构建器,但是我想用style=""
覆盖背景不透明度值。
我读过How do I give text or an image a transparent background using CSS?,还通过互联网进行搜索,发现的唯一答案是使用rgba(r,g,b,a)
函数。
那么我如何使r,g,b继承自先前的值(除了alpha(不透明度))?如果不可能,是否有任何解决方法可以实现同一目标?而且,如果无法使用纯CSS解决方案,是否可以使用javascript解决任何问题?
解决方法
有一种方法可以在JavaScript中实现:
-
首先,定位您的元素:
var elem = document.querySelector('#maincontent');
-
然后,您可以捕获当前的背景色:
var oldColor = getComputedStyle(elem).backgroundColor;
-
然后,更新颜色:
var newColor ='rgba'+ oldColor.slice(3,-1)+',0.5)';
//以上行会将颜色从rgb转换为rgba
// rgb(16,14,23)=> rgba(16,14,23,0.5)
-
现在,您可以更新目标元素的背景色:
elem.style.backgroundColor = newColor;