如何有选择地将样式表添加到UIWebView?

时间:2013-09-10 23:36:35

标签: ios css uiwebview stylesheet

我正在尝试编写HTML,这会导致UIWebView在加载时应用特定于设备的样式表。

在我的HTML模板的元素中,我定义了以下Javascript:

    <script type="text/javascript">
        window.onload = function()
        {
            var newStylesheetLink = document.createElement('link');
            newStylesheetLink.rel = 'stylesheet';
            newStylesheetLink.type = 'text/css';

            if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i))
            {
                newStylesheetLink.href='about~iphone.css');
            }
            else
            {
                newStylesheetLink.href='about~ipad.css');
            }

            document.head.appendChild(newStylesheetLink);
        };
    </script>

我已经确认在UIWebView加载时确实调用了这个函数,并且设备检测工作正常;但是newStylesheetLink元素var引用的样式表没有被应用到UIWebView的内容(也就是说,显然,它不会加载引用的CSS文件,或者如果它加载,则将它作为子元素附加到head元素上不会导致UIWebView的内容更新。

有什么想法吗?

谢谢!

卡尔

1 个答案:

答案 0 :(得分:0)

好吧,经过多次试验和错误,我发现如果不是设置链接的href:

newStylesheetLink.href=<value>;

我改为设置:

newStylesheetLink.setAttribute('href', <value>);
一切正常。换句话说,如果我使用setAttribute方法而不是.href表示法,它就可以工作。为什么这应该是如此,特别是因为.rel和.type赋值工作得很好。 (可能是在iOS中,setAttribute方法解析了应用程序包中样式表的路径,而.href赋值却没有?)

所以,这个修改后的脚本实际上有效:

<script type="text/javascript">
    window.onload = function()
    {
        var newStylesheetLink = document.createElement('link');

        newStylesheetLink.rel = 'stylesheet';
        newStylesheetLink.type = 'text/css';

        if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i))
        {
            newStylesheetLink.setAttribute('href', 'about~iphone.css');
        }
        else
        {
            newStylesheetLink.setAttribute('href', 'about~ipad.css');
        }

        document.head.appendChild(newStylesheetLink);
    };
</script>