javascript - 无法在 iOS 中使用 getComputedStyle 访问样式

标签 javascript ios styles

好的,所以我设计了这个函数来从指定元素返回所需的计算样式。它适用于我测试过的所有桌面浏览器,但是,它不适用于移动 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.getComputedStyledocument.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/

相关文章:

javascript - jqGrid - 绑定(bind)键更改箭头和 Tab 键行为

php - HTML5 localStorage & 同源策略 : sometimes it works, 有时它不会

ios - 在 iOS 应用程序上阻止垃圾邮件发送者

ios - RestKit RKDynamicObjectMapping 仅适用于第一个 JSON 结果

ios - UIView 的空中打印生成白页

html - 添加CSS类时如何强制Angular更新元素CSS

javascript - 如何限制 html 数字输入(实时)中允许的数字数量?

javascript - 如何获取像 jQuery 这样的默认 CSS 属性?

java - Android 在 ThemeOverlay.AppCompat.Dark.ActionBar 中将工具栏/小部件背景更改为黑色

javascript - 无法使用 jquery 触发 'hover' 事件