2012-06-19 113 views
3

我試圖檢測移動設備,iPhone和iPad的方向更改。orientationchange事件不起作用

我使用下面的代碼:

$(window).bind("orientationchange", function (event) { 
    alert(event.orientation); 

    position = $.event.special.orientationchange.orientation(); 

    event.preventDefault(); 
}); 

這裏戒備即event.orientation的值顯示爲「未定義」,其中正如我在一些後已閱讀,它以檢測取向支持。 另外在jQuery文檔中,它被寫入更好地使用「event.orientation」而不是「window.orientation」,但沒有一個返回所需的結果,都返回「undefined」。

所以我用「$ .event.special.orientationchange.orientation();」檢測方向。

但我想使用jquery文檔中定義的功能作爲event.orientation。如link

同樣在我的代碼中,「$ .mobile.orientationChangeEnabled」設置爲true,如上面的鏈接所示。

請給我建議任何可能的解決方案。

任何幫助,將不勝感激。

在此先感謝。

回答

0

試試這個:

$(window).bind('orientationchange',function(){ 
    if(event.orientation == 'portrait'){ 
     alert('portrait'); 
    } 
    else if(event.orientation == 'landscape') { 
     alert('landscape'); 
    } 
}); 
1

老問題,但以防萬一別人遇到它,你必須使用window.orientation,那就是以度表示:

portrait: 0 
portrait (upside down): 180 
landscape: (counterclockwise): 90 
landscape: (clockwise): -90 
0
$(window).on("orientationchange", function (event) { 
0

event.orientation不總是設置。我在IOS Safari中遇到了這個「未定義」的問題。相反,嘗試使用window.orientation:

//trigger a button click when orientation is changed to landscape mode 
$(window).on('orientationchange', function(event) { 
    if (window.orientation == 90 || window.orientation == -90) { 
     $('.close-button').click(); 
    } 
}); 

window.orientation可以是0或180(肖像模式),或90或-90(橫向模式)