导读:迩来看了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. 即假如数组字面量元素荟萃的最后是逗号,逗号会被忽略掉。