jQuery Mobile orientation change event
jQuery Mobile orientationchange event
The orientationchange event is triggered when the user rotates the mobile device vertically or horizontally.
To use the orientationchange event, attach it to the window object:
$(window).on("orientationchange",function(){ alert("方向有改变!"); });
The callback function can have one parameter, an event object, which returns the orientation of the mobile device: "portrait" (the device remains in a vertical position) or "landscape" (the device remains in a horizontal position):
Example
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> <script src="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <script> $(document).on("pagecreate",function(event){ $(window).on("orientationchange",function(event){ alert("方向改变为: " + event.orientation); }); }); </script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>orientationchange 事件</h1> </div> <div data-role="main" class="ui-content"> <p>请试着旋转您的设备!</p> <p><b>注释:</b>您必须使用移动设备或者移动模拟器来查看该事件的效果。</p> </div> <div data-role="footer"> <h1>页脚文本</h1> </div> </div> </body> </html>
Running instance »
Click the "Run Instance" button to view the online instance
Since the orientationchange event is bound to the window object, we can use the window.orientation property to set different styles to distinguish between portrait and landscape views:
Example
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> <script src="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <script> $(document).on("pagecreate",function(event){ $(window).on("orientationchange",function(){ if(window.orientation == 0) { $("p").text("方向已经变为 portrait!").css({"background-color":"yellow","font-size":"300%"}); } else { $("p").text("方向已经变为 landscape!").css({"background-color":"pink","font-size":"200%"}); } }); }); </script> </head> <body> <div data-role="page"> <div data-role="header"> <h1> orientationchange 事件</h1> </div> <div data-role="main" class="ui-content"> <p>请试着旋转您的设备!</p> <p><b>注释:</b>您必须使用移动设备或者移动模拟器来查看该事件的效果。</p> </div> <div data-role="footer"> <h1>页脚文本</h1> </div> </div> </body> </html>
Running instance »
Click the "Run Instance" button to view the online instance
The window.orientation property returns 0 for portrait view and 90 or -90 for landscape view. |