使用JS获取元素CSS3背景颜色渐变

5

目前,我使用以下JS(jQuery)查找其他几个div的背景颜色(作为rgb):

$theColor = $(this).css("background-color");

除了CSS3渐变效果外,它的表现非常完美。

举个例子,我有以下CSS代码来使一个div的背景看起来像一个便签:

background: #FFFAAD; /* old browsers */

background: -moz-linear-gradient(top, #FFFAAD 0%, #FFF47D 100%); /* firefox */

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FFFAAD), color-stop(100%,#FFF47D)); /* webkit */

background: gradient(linear, left top, left bottom, color-stop(0%,#FFFAAD), color-stop(100%,#FFF47D));

filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#FFFAAD', endColorstr='#FFF47D',GradientType=0 ); /* ie */

jQuery似乎没有捕获到任何内容。

我该如何使用jQuery找到CSS3渐变中使用的至少一种颜色?我对JS相对较新,请多多包涵。

谢谢。


渐变不是一种颜色,而是一种背景图像。检查 background-color 不会告诉你任何关于背景图像的信息。 - robertc
没有设置背景图片,这完全是CSS3。我怀疑这些渐变不是作为图像存储的(甚至可能无法作为图像存储)。 - Harley
1
有一个背景图片,渐变是背景图片。这就是为什么你的CSS中写的是background: -moz-linear-gradient而不是background-color: -moz-linear-gradient的原因。 - robertc
这是涵盖渐变的CSS规范,可以查看一下它的名称:http://dev.w3.org/csswg/css3-images/#gradients - robertc
3个回答

2

这是一个不错的链接,但在可能解决问题的那一部分,它说:'get'并不是真正需要的,因为我们只想能够覆盖设置样式,而不是真正获取它。 - robertc
OP在哪里说的?他们的问题是关于获取值的。 - Erick Petrucelli

2
你需要为渐变(gradient)创建一个cssHook(例如,jQuery已经为透明度(opacity)实现了一个hook)。
请参见:http://api.jquery.com/jQuery.cssHooks/ 按要求,以下是检索颜色的示例代码:
(function($){   

    if ( !$.cssHooks ){
        //if not, output an error message
        alert("jQuery 1.4.3 or above is required for this plugin to work");
        return;
    }
    div = document.createElement( "div" ),
    css = "background-image:gradient(linear,left top,right bottom, from(#9f9), to(white));background-image:-webkit-gradient(linear,left top,right bottom,from(#9f9),to(white));background-image:-moz-gradient(linear,left top,right bottom,from(#9f9),to(white));background-image:-o-gradient(linear,left top,right bottom,from(#9f9),to(white));background-image:-ms-gradient(linear,left top,right bottom,from(#9f9),to(white));background-image:-khtml-gradient(linear,left top,right bottom,from(#9f9),to(white));background-image:linear-gradient(left top,#9f9, white);background-image:-webkit-linear-gradient(left top,#9f9, white);background-image:-moz-linear-gradient(left top,#9f9, white);background-image:-o-linear-gradient(left top,#9f9, white);background-image:-ms-linear-gradient(left top,#9f9, white);background-image:-khtml-linear-gradient(left top,#9f9, white);";    
    div.style.cssText = css;


    $.support.linearGradient =
    div.style.backgroundImage.indexOf( "-moz-linear-gradient" )  > -1 ? '-moz-linear-gradient' :
    (div.style.backgroundImage.indexOf( "-webkit-gradient" )  > -1 ? '-webkit-gradient' :
    (div.style.backgroundImage.indexOf( "linear-gradient" )  > -1 ? 'linear-gradient' : false));
    if ( $.support.linearGradient)
    {
      $.cssHooks['linearGradientColors'] = { 
        get: function(elem){
          var currentStyle=$.css(elem, 'backgroundImage'),gradient,colors=[];
          gradient=currentStyle.match(/gradient(\(.*\))/g);
          if(gradient.length)
          {
            gradient=gradient[0].replace(/(linear|radial|from|\bto\b|gradient|top|left|bottom|right|\d*%)/g,'');
            colors= jQuery.grep(gradient.match(/(rgb\([^\)]+\)|#[a-z\d]*|[a-z]*)/g),function (s) { return jQuery.trim( s )!=''})
          }
          return colors;
        }
    };
 }
})(jQuery);

正如我所说,这只是一个使用cssHooks的示例,不适用于生产环境。在我的ff、chrome、IE9和safari中运行良好。

如果您遵循RickV发布的链接,可以找到一个set-function。

用法:$('选择器').css('linearGradientColors')
返回:一个包含颜色的数组


你还需要编写一些JavaScript代码来返回钩子的get中的值吗? - robertc
当然可以。如果你需要的是jQuery中还没有实现的功能,你就必须自己编写代码,而渐变效果并没有被实现。 - Dr.Molle
这里的问题是你需要编写什么来在jQuery中实现它。 - robertc
问题是“我如何使用jQuery”,我的答案是“cssHooks”,因为这是在这里使用jQuery的方法。 - Dr.Molle
问题是:“如何使用JS获取元素的CSS3背景颜色渐变。” - robertc
显示剩余4条评论

-1

您可以通过查看元素的background-image属性并提取列出的颜色来提取渐变中使用的颜色。这里有一个例子,它使用了此帖子中的CSS颜色匹配正则表达式。我刚刚将代码绑定到具有背景的元素的onclick事件上:

$("div").bind("click", function() {
    window.alert('Background color: ' + ($(this).css('background-color')));
    var re = /(#([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(yellow)|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))/g;
    var colors = ($(this).css('background-image')).match(re);
    for (var i=0; i < colors.length; i++) {
        window.alert('Gradient colour: ' + colors[i]);
    }
});

请注意,此正则表达式适用于CSS2颜色,因此不会匹配任何rgba()hsla()颜色。但如果有必要,您应该可以扩展它。

这里的jQuery部分是什么(由OP请求)?检索当前样式?此外,如果您忽略它,cssHooks是在这里使用的方法,而不是这个解决方案。 - Dr.Molle
@DrMolle $(this).css('background-color')是相关的jQuery代码。 不需要对 cssHooks 做任何操作,因为所需信息已经在标准的jQuery中提供了。 - robertc
如果有人要求使用jQuery创建一个警告框,你可以建议使用$(window)[0].alert('an alert with jquery');。但我相信最终他不仅需要了解一些颜色。cssHooks可以让他扩展jQuery以满足自己的需求,而不会失去已知的可用性。 - Dr.Molle
@DrMolle 抱歉,我在之前的评论中应该说$(this).css('background-image'),因为问题在于$(this).css('background-color')没有返回他想要的信息。在这种情况下,我该如何使用cssHooks?相对于使用$(this).css('background-image')返回信息,它有什么好处?如果放在评论中限制太大,请在您的答案中更新代码。 - robertc
好处很简单,我可以使用jQuery方式获取CSS值,而无需在某个地方定义任何打破常规jQuery工作流程的函数。我已经在我的帖子中更新了一个示例。 - Dr.Molle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接