好的,所以我设计了这个函数来从指定元素返回所需的计算样式。它适用于我测试过的所有桌面浏览器,但是,它不适用于移动 safari。如果我将 getComputedStyle 调用记录回控制台,它是一个很棒的 [object CCStyleDeclaration],但是当我记录 getPropertyValue 调用时,它只是返回“null”而不是正确的样式。任何帮助都会很棒。谢谢!
Utils.getStyle = function(element, style){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(element, "").getPropertyValue(style);
}else if(element.currentStyle){
style = style.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = element.currentStyle[style];
};
return strValue;
};
最佳答案
如果我对 window.getComputedStyle
与 document.defaultView.getComputedStyle
的评论有任何实质内容,我会在自己的库中使用此函数:
getComputedStyle : function(element){
var styles = element.currentStyle || getComputedStyle(element, null);
return styles;
}
适应您的函数签名:
Utils.getStyle = function(element, style){
var styles = element.currentStyle || getComputedStyle(element, null);
// Prevent a 'Cannot read property X of null' error
if(styles != null){
return styles[style];
} else {
return null;
}
}
很遗憾,我无法在 iOS 中对此进行测试,但我很想知道它是否有效。
关于javascript - 无法在 iOS 中使用 getComputedStyle 访问样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206924/