问题
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;
};
回答1:
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;
}
Adapted to your function signature:
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;
}
}
I can't test this in iOS unfortunately, but I'm interested to know if it works.
来源:https://stackoverflow.com/questions/12206924/unable-to-access-style-with-getcomputedstyle-in-ios