导读:近来看了Dean的Convert any colour value to hex in MSIE,终于解决了根据关键字获取颜色rgb值的问题。 !DOCTYPE htmlhtml xmlns=http://www.w3.org/1999/xhtmlheadmeta http-equiv=Content-Type content=text/html; charset=gb2312 /title Java Script 颜
近来看了Dean的“Convert any colour value to hex in MSIE”,终于解决了根据关键字获取颜色rgb值的问题。
如果是关键字形式那就要另外想方法了,可以用一个字典对象来匹配颜色值,但这样程序会变得很庞大。 ps:可以到这里看所有颜色名对应的数值。 近来dean发表了“Convert any colour value to hex in MSIE”,终于解决了这个难题。 其中的关键是利用queryCommandValue("ForeColor")来获取颜色值(或许做过编辑器的会比较熟悉)。 queryCommandValue的作用是返回document、range或current selection对于给定命令的当前值。 而ForeColor命令是设置或获取文本时的前景色。
其他支持document.defaultView的可以直接用getComputedStyle获取color。 从上面各个浏览器获取颜色值的结果可知获取的值都是RGB形式的值,所以可以直接用GetData转换: ret = GetData(document.defaultView.getComputedStyle(frag, null).color); 注意除了ff,如果元素没有插入dom,用getComputedStyle是获取不了color的,所以元素创建时要顺便插入到body中。
在GetStep用GetColor获得颜色值之后,再根据step就可以获得步长了: var colors = [], start = GetColor(start), end = GetColor(end), stepR = (end[0] - start[0]) / step, stepG = (end[1] - start[1]) / step, stepB = (end[2] - start[2]) / step; 再根据步长生成集合: for(var i = 0, r = start[0], g = start[1], b = start[2]; i < step; i++){ colors[i] = [r, g, b]; r += stepR; g += stepG; b += stepB; } colors[i] = end; 正确的颜色值是在0到255之间的,而且是不带小数的,需要修正一下: return $$A.map(colors, function(x){ return $$A.map(x, function(x){ return Math.min(Math.max(0, Math.floor(x)), 255); });});
程序支持设置多个颜色的连续变换: for(var i = 0, n = len - 1; i < n; i++){ var steps = GetStep( colors[i], colors[i+1], step ); i < n - 1 && steps.pop(); ret = ret.concat(steps); } 注意的是各次变换之间要去掉重复的颜色(steps.pop())。
在测试过程中还发现一个数组的问题,运行alert([,,].length),在ie会返回3,其他会返回2。 在mozilla的Array_Literals部分查到: If you include a trailing comma at the end of the list of elements, the comma is ignored. 即如果数组字面量元素集合的最后是逗号,逗号会被忽略掉。