网站首页学无止境JS

iPad Android系统下,平板设备判断横竖屏,以及横竖屏变化之

发布时间:2015-04-15 11:11:35编辑:songlin阅读(113)

      平板开发中,经常需要用到设备判断横屏竖屏,以及屏幕发生横竖变化时候所触发的一些事件。

      基本上使用下面的js就可以了。

    1. // Detect whether device supports orientationchange event, otherwise fall back to 
    2. // the resize event. 
    3.  
    4. var supportsOrientationChange = "onorientationchange" in window, 
    5.     orientationEvent = supportsOrientationChange ? "orientationchange" : "resize"
    6.  
    7. window.addEventListener(orientationEvent, function() { 
    8.     alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation); 
    9. }, false); 

      无论是ipad还是安卓:

      可以在function里面实装切换后的事件,比如横竖屏不同,画面的布局设计,css使用不同等等。

      ※你可以使用window.orientation来判断切换之后到底是横屏还是竖屏。

      但是: 关于上面的代码,有几项是需要注意的。

      1, window.orientation

      经过测试,在ipad,和andriod系统上面,window.orientation来判断横竖屏用得值正好相反。

    window.orientation值参考:
      window.orientation 横竖屏结果
    ipad 90或者-90 横屏
    ipad 0 或者180 竖屏
    Andriod 0 或者180 横屏
    Andriod 90或者-90 竖屏
     

      2,如何判断自己的设备是ipad还是安卓

      一个土办法: 从 navigator.userAgent 里面截取字符串。

      具体参照:

      http://stackoverflow.com/questions/1649086/detect-rotation-of-android-phone-in-the-browser-with-javascript

      一个完整的例子:

    1. > 
    2. <html> 
    3. <head> 
    4. <meta charset="utf-8"> 
    5. <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> 
    6. <title> 横竖屏测试网页 title> 
    7. <script type="text/javascript"> 
    8.  
    9. // Detect whether device supports orientationchange event, otherwise fall back to 
    10. // the resize event. 
    11. var supportsOrientationChange = "onorientationchange" in window, 
    12.     orientationEvent = supportsOrientationChange ? "orientationchange" : "resize"; 
    13.  
    14. // 监听事件 
    15. window.addEventListener(orientationEvent, function() { 
    16.     var ua = navigator.userAgent; 
    17.     var deviceType=""
    18.  
    19.     //判断设备类型  
    20.  
    21.     if (ua.indexOf("iPad") > 0) { 
    22.        deviceType = "isIpad"
    23.     } else if (ua.indexOf("Android") > 0) { 
    24.        deviceType = "isAndroid"
    25.     } else { 
    26.        alert("既不是ipad,也不是安卓!"); 
    27.        return; 
    28.     } 
    29.     
    30.  
    31.      // 判断横竖屏  
    32.  
    33.      if ("isIpad" == deviceType) { 
    34.        if (Math.abs(window.orientation) == 90) { 
    35.            alert("我是ipad的横屏"); 
    36.        } else { 
    37.            alert("我是ipad的竖屏"); 
    38.        } 
    39.     } else if ("isAndroid" == deviceType ) { 
    40.        if (Math.abs(window.orientation) != 90) { 
    41.            alert("我是安卓的横屏"); 
    42.        } else { 
    43.            alert("我是安卓的竖屏"); 
    44.        } 
    45.     } 
    46. }, false); 
    47. script> 
    48. head> 
    49.  
    50.  
    51. <body> 
    52. 横竖屏测试网页 
    53. body> 
    54. html>