问题描述
好的,所以我将这个函数设计为从指定元素返回所需的计算样式.它适用于我测试过的所有桌面浏览器,但是,它不适用于移动 safari.如果我将 getComputedStyle 调用记录回控制台,它是一个很好的 [object CCStyleDeclaration],但是当我记录 getPropertyValue 调用时,它只返回null"而不是正确的样式.任何帮助都会很棒.谢谢!
Ok, so I have this function designed to return a desired computed style from a specified element. It works in all desktop browsers that I have tested, however, it does not work in mobile safari. If I log the getComputedStyle call back to the console it is a [object CCStyleDeclaration] which is great, but when I log the getPropertyValue call it simply returns "null" instead of the correct style. Any help would be fantastic. Thanks!
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
的评论有任何实质内容,我在自己的库中使用这个函数:
In the case my comment about window.getComputedStyle
vs document.defaultView.getComputedStyle
has any substance, I use this function in my own library:
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 中对此进行测试,但我很想知道它是否有效.
I can't test this in iOS unfortunately, but I'm interested to know if it works.
这篇关于无法在 iOS 中使用 getComputedStyle 访问样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!