jquery获取背景渐变色 [英] Jquery get background gradient color

查看:30
本文介绍了jquery获取背景渐变色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取背景颜色并将其放入body,例如我的背景与FirstColor类中的一样:

I want get background color and putting it in body, for example my background is as in class FirstColor:

.FirstColor{
    background-image: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#ECAA63), to(#E36D0A));
}

现在我想在 .FirstColor 类中获取背景的颜色 #ECAA63#E36D0A 并将它们替换为 body 中的颜色

Now i want get colors #ECAA63 and #E36D0A of background in class .FirstColor and replace they instead colors in body

body 为:

body{
    background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 350, from(#CEEEEE), to(#98BFF1));
}

.FirstColor 类的它们替换为 body 为:

Replace they of class .FirstColor to body as:

#ECAA63 - 代替 -> #CEEEEE
#E36D0A - 相反 -> #98BFF1

#ECAA63 - instead -> #CEEEEE
#E36D0A - instead -> #98BFF1

我试图获取背景颜色 ac:http://jsfiddle.net/rKQwu/ 但不能完成.

I tried to get background color ac: http://jsfiddle.net/rKQwu/ But can not done.

推荐答案

首先,为什么不直接切换 div 的类,而不是直接修改样式?

First of all, why not just switch the classes of the divs instead of modifying the styles directly?

但如果有理由需要这样做,那么您需要从样式值解析 fromto 值.正如我在评论中所说,你的代码在你的 jsfiddle 中似乎很好;问题似乎是您为库选择了 MooTools 而不是 jQuery,在我切换之后,它按预期工作.我不太了解 Webkit 标准,但是在 Chrome 23 上,十六进制值被转换为 rgb(r, g, b) 样式的三元组,所以我写了一些代码来解析它们:

But if there's a reason you need to do it, then you need to parse the from and to values from the style value. As I said in my comment, your code seems to be fine in your jsfiddle; the problem appears to be that you selected MooTools instead of jQuery for your library, and after I switched that, it worked as expected. I don't know much about the Webkit standard, but on Chrome 23, the hex values are converted to rgb(r, g, b) style triplets, so I wrote a little code to parse those out:

var bgGrad = $('.FirstColor').css("background");
var parseRgb = (function (rgbStr) { return rgbStr.match(/rgb\(([0-9]+), ([0-9]+), ([0-9]+)\)/); });
var fromStr = bgGrad.match(/from\((.*)\),/)[1];
var fromRgb = parseRgb(fromStr);

var toStr = bgGrad.match(/to\((.*)\)\)/)[1];
var toRgb = parseRgb(toStr);

alert('From rgb: ' + fromRgb.slice(1,4) + '\nTo rgb: ' + toRgb.slice(1, 4));
​

在此代码之后(在 jsfiddle 此处),fromRgbtoRgb 是 3 个 rgb 值的数组.一旦按照您认为合适的方式提取和修改值后,重建新的背景渐变字符串应该是微不足道的.我不太了解这段代码对不同情况的健壮性,但对于您提供的示例,它在上述 Chrome 版本上对我来说似乎工作正常.

After this code (in the jsfiddle here), fromRgb and toRgb are arrays of 3 rgb values. It should be trivial to rebuild a new background gradient string once the values are extracted and modified as you see fit. I don't know enough to know how robust this code is to different cases, but it seems to work fine for me on the above Chrome version for the example you gave.

这篇关于jquery获取背景渐变色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆