mko*_*yak 2 javascript jquery computed-style
我试图使用以下代码在IE中获取RGB背景颜色:
function getStyle(elem, name) {
// J/S Pro Techniques p136
if (elem.style[name]) {
return elem.style[name];
} else if (elem.currentStyle) {
return elem.currentStyle[name];
}
else if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
} else {
return null;
}
}
var $b = $("<button>");
$b.css("backgroundColor", "ButtonFace");
$("body").append($b);
alert("button bg color is: "+ getStyle($b[0],"backgroundColor"));
//alerts 'buttonface'
Run Code Online (Sandbox Code Playgroud)
这不会像firefox那样返回rgb颜色值,它会返回'buttonface',这对我来说是无用的.
我一直在研究"getStyle"函数的跨浏览器实现,我的功能尚未完成,但我可以帮助您解决IE中的这个特定问题.
对于计算出的backgroundColor,我使用的是中提出的破解这个页面,它使用IE特定的queryCommandValue方法来获得BackColor一个选择.
关于你发布的实现,我建议首先检查标准getComputedStyle方法是否document.defaultView存在,因为有些浏览器如Opera,提供IE特定currentStyle对象的兼容性.
所以我重构了你的功能并包含了IE hack:
function getStyle(elem, name) {
if (document.defaultView && document.defaultView.getComputedStyle) {
name = name.replace(/([A-Z])/g, "-$1");
name = name.toLowerCase();
s = document.defaultView.getComputedStyle(elem, "");
return s && s.getPropertyValue(name);
} else if (elem.currentStyle) {
if (/backgroundcolor/i.test(name)) {
return (function (el) { // get a rgb based color on IE
var oRG=document.body.createTextRange();
oRG.moveToElementText(el);
var iClr=oRG.queryCommandValue("BackColor");
return "rgb("+(iClr & 0xFF)+","+((iClr & 0xFF00)>>8)+","+
((iClr & 0xFF0000)>>16)+")";
})(elem);
}
return elem.currentStyle[name];
} else if (elem.style[name]) {
return elem.style[name];
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
希望很快我会发布一个更通用的实现,但这足以解决您的backgorundColor问题.
您可以在此处测试上述功能.
| 归档时间: |
|
| 查看次数: |
2158 次 |
| 最近记录: |