您可以创建一个隐藏的画布元素,其宽度为 100 像素,高度为 1 像素,从前景色(本例中为黑色)到背景色(本例中为白色)呈线性渐变。
然后您可以使用 ctx.getImageData() 来获取渐变上给定点的颜色。您使用的 x 坐标将与 div 的不透明度相同,但乘以 100。
getImageData() 返回的数据可以直接用于 'rgba' 格式的背景颜色值。
<div id="myDiv" style="opacity:0.3;"></div>
然后是javascript:
//get the div's opacity
var myDiv = document.getElementById('myDiv');
var divOpc = myDiv.style.opacity;
/*
To get the opacity, you'll probably want to use
jquery's $(myDiv).css('opacity'), unless the opacity is in
the 'style' attribute.
If you wanted to keep it vanilla JS, you could use getComputedStyle().
*/
//create hidden canvas
var cvs = document.createElement('canvas');
cvs.style.display = 'none';
cvs.width = 100;
cvs.height = 1;
document.body.appendChild(cvs);
//give canvas a gradient
var ctx = cvs.getContext('2d');
var grd = ctx.createLinearGradient(0,0,100,0);
grd.addColorStop(0,'black'); //foreground colour
grd.addColorStop(1,'white'); //background colour
/*
If you wanted to make this dynamic, you would get the
current background colour of the foreground/background element,
instead of hard-coding a colour.
*/
ctx.fillStyle = grd;
ctx.fillRect(0,0,100,1);
//The Magic!
var imgData = ctx.getImageData((100 - divOpc*100),0,1,1);
var formattedBG = 'rgba('+imgData.data[0]+','+imgData.data[1]+','+imgData.data[2]+',1)';
//Do something with that discovered bg colour.
//As an example: Give the background to a different div
var bgRecipient = document.getElementById('bgRecipient');
bgRecipient.style.backgroundColor = formattedBG;
工作 jsFiddle:http://jsfiddle.net/zbC9u/6/
编辑:我更新了小提琴以更加匹配你的。