Unable to access style with getComputedStyle in iOS

穿精又带淫゛_ 提交于 2019-12-22 12:44:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!