从线性渐变颜色值中获取背景颜色

Out*_*ker 10 jquery

我怎么能得到color-codelinear gradient使用值jQuery.Suppose如果我有一个linear gradient

background:linear-gradient(to right, #fff 87%,rgba(238,237,233,0) 100%);
Run Code Online (Sandbox Code Playgroud)

我怎么能从这里提取颜色代码.我应该得到最终输出,就像#fff在这种情况下..我尝试使用

$('selector').css('background-color');
Run Code Online (Sandbox Code Playgroud)

这对我没有帮助我得到颜色代码.有人可以帮我解决这个问题.谢谢.. :)

Pog*_*dis 1

一种可能的解决方案是使用“选择器”class|id 创建一个画布元素来设置其样式。

然后你可以在画布上建立像素的 RGBA.. 非常“hacky”,但这是我的小大脑唯一能想到的!

像这样的东西(未经测试!):

假设你的 html 看起来像这样:

<style>
.background_element{
background:linear-gradient(to right, #fff 87%,rgba(238,237,233,0) 100%);
}
</style>
Run Code Online (Sandbox Code Playgroud)

然后你想检查背景颜色..所以我们创建一个canvas对象来克隆当时的div。

var canvas = document.createElement('canvas');
//apply width and heigh 1px
canvas.css('background-color', $('.background_element').style.backgroundColor);
Run Code Online (Sandbox Code Playgroud)

那么我们就无法获取画布上像素的颜色。

var pixelData = this.canvas.getContext('2d').getImageData(1, 1, 1, 1).data;
console.log('R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3]);
Run Code Online (Sandbox Code Playgroud)

这会将 RGBA 记录到控制台..也许..

- 注意:我当然不推荐将其用于生产环境,这仅仅是一个概念证明!

灵感

或者

您可能会非常喜欢并真正剥离 RGBA HTMLelement.prototype.alpha!:)

就像是 :

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;
        console.log("rgba(" + [match[1],match[2],match[3],a].join(',') +")");
      }
Run Code Online (Sandbox Code Playgroud)

再次非常混乱,但很有可能这会更加精确!