如何在UIWebView中处理JavaScript onorientationchange事件

5

有没有人能帮我解决在iPhone上通过uiwebview访问网页时如何处理方向改变事件的问题?相关内容与IT技术有关。

我正在尝试捕获Javascript的onorientationchange事件。我尝试了以下代码:

<style type="text/css" media="only screen and (max-device-width: 480px)">
    .portrait
    {
        width: 300px;
        padding: 0 15px 0 5px;
    }
    .landscape
    {
        width: 460px;
        padding: 0 15px 0 5px;
    }
</style>

<script type="text/javascript">
    window.onload = orientationchange;
    window.onorientationchange = orientationchange;
    function orientationchange() {
        if (window.orientation == 90
            || window.orientation == -90) {
            document.getElementById('contents').className = 'landscape';
        }
        else {
            document.getElementById('contents').className = 'portrait';
        }
    }
</script>

// and I have a div inside html

<div id="contents">
    my contents and description... e.t.c, and e.t.c...
</div>

在Safari中运行良好,但是当我使用uiwebview访问页面时,方向更改事件未被捕获,我的期望功能无法实现。

3个回答

4
我想向您介绍这篇帖子:"iphone-uiwebview-local-resources-using-javascript-and-handling-onorientationchang",在被接受的答案下方直接回答了您的问题:处理应用程序代码中的方向更改,并使用JavaScript注入更改。我引用以下内容,希望作者不会介意:
“针对您在UIWebView中未调用onorientationchange处理程序的第二个问题的答案:
我注意到window.orientation属性无法正常工作,而且window.onorientationchange处理程序不会被调用。大多数应用程序都会遇到此问题。可以通过在包含UIWebView的视图控制器的willRotateToInterfaceOrientation方法中设置window.orientation属性并调用window.onorientationchange来解决此问题:“

我不需要本地资源,我只想在我的HTML的JavaScript中捕获方向更改事件。 - Waqas Raja
我从我之前尝试向你展示但未能成功的帖子中添加了一句引用。实际上,这就是你所述的问题。 - Nick Weaver
是的,谢谢。我的问题已经解决了。但在应用程序中消耗启用方向的HTML页面感觉很奇怪。 - Waqas Raja
不客气。是的,本来不应该这样,但这是解决这个 bug 的好方法。 - Nick Weaver

1

谢谢。

另一种写法是:

var onorientationchange = function()    {
    document.getElementById('contents').className =
      Math.abs(window.orientation == 90)? "landscape" : "portrait";
}
window.onload = function() {
    window.onorientationchange = window.onorientationchange
}

看起来不错,我稍后会检查它并告诉你它是否有效。 - Waqas Raja
谢谢你的回答,但是代码中有一个括号错误。你需要使用Math.abs(window.orientation) == 90,而不是比较的绝对值... - tyler

1
将以下代码放入viewDidLoad中:
[[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasOrientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

- (void)hasOrientationChanged:(NSNotification *)notification {
    UIDeviceOrientation currentOrientation; 
    currentOrientation = [[UIDevice currentDevice] orientation];
    if(currentOrientation == UIDeviceOrientationLandscapeLeft){
        NSLog(@"left");
    }

    if(currentOrientation == UIDeviceOrientationLandscapeRight){
        NSLog(@"right");
    }

}

现在你可以使用正确的方向调用你的 Webview :)

是的,在应用程序中是正确的。但我怎么知道在我的HTML页面中呢? - Waqas Raja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接