2011-03-07 23 views
4

任何人都可以幫助我如何在JavaScript處理方向變化事件,通過一個UIWebView在iphone訪問時?如何處理內部的UIWebView JavaScript的onorientationchange事件

我試圖捕捉onorientationchange事件的JavaScript。我試過下面的代碼。

<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的方向改變事件的頁面沒有被捕獲和我期望的功能不能被來達到的。

回答

4

我想指向this post: "iphone-uiwebview-local-resources-using-javascript-and-handling-onorientationchang",直接在接受的答案下面的答案會向您的問題致敬:處理應用程序代碼中的方向更改並使用javascript注入更改。我引述希望作者不會介意:

「解答您的onorientationchange處理程序沒有被調用在UIWebView中的第二個問題:

我注意到window.orientation屬性不正常工作,在window.onorientationchange處理程序不會被調用大多數應用程序受此問題,這可以通過包含您的UIWebView的視圖控制器的willRotateToInterfaceOrientation方法設置window.orientation屬性和調用window.onorientationchange固定:」

+0

我不需要當地的資源,我只是想捕捉的方向變化事件在我的HTML的JavaScript – 2011-03-07 14:53:53

+0

我加了一個引號從我試着不成功顯示您的帖子。這實際上是你所說的問題。 – 2011-03-07 14:59:27

+0

耶謝謝;我的問題解決了。但在應用程序中使用定向啓用的html頁面很奇怪。 – 2011-03-07 18:39:46

1

謝謝你。

另一種方式來寫是這樣的:

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

它看起來不錯,我會稍後檢查它,並讓你知道它是否有效。 – 2011-03-20 04:50:33

+0

感謝您的答案,但它沒有奏效。 – 2011-03-22 12:45:20

+0

感謝您的回答,但代碼中有一個parens錯誤。你想Math.abs(window.orientation)== 90,比較不絕...... – tyler 2011-10-31 19:38:44

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用正確的方向:)

+0

是的,這是正確的應用程序。但我怎麼能在我的HTML頁面知道? – 2011-12-05 18:21:07