gpt4 book ai didi

javascript - 获取半透明黑色 div 的结果背景颜色?

转载 作者:行者123 更新时间:2023-11-28 12:15:17 25 4
gpt4 key购买 nike

我有一个 div 元素,它有一个黑色背景颜色集和一个小的不透明度以融入各种网站背景(白色、灰色、绿色等)。有什么办法可以获得该元素的计算颜色?我指的是用户可以看到的颜色(不透明度 + 元素背景色 + 网站背景色的组合)。

当然这必须通过 JavaScript 来完成,但我找不到执行此操作的方法或插件。我知道 JS 中的 backgroundColor 但它只会返回 background-color CSS 值:black

这是一个例子: http://jsfiddle.net/N6EB8/

非常感谢!

PS:希望我说得足够清楚。如果没有,请告诉我。

最佳答案

您可以创建一个隐藏的 Canvas 元素,其宽度为 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/

编辑:我更新了 fiddle 以更符合你的。

关于javascript - 获取半透明黑色 div 的结果背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23800643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com