iPad Android系统下,平板设备判断横竖屏,以及横竖屏变化之后的事件触发(html + javascript)

闭月羞花猫: 2012年1月于 河西新城科技园

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


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

<script>

// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.

var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation);
}, false);
</script>


无论是ipad还是安卓:

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

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


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

1, window.orientation

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

window.orientation值参考:
 window.orientation横竖屏结果
ipad90或者-90横屏
ipad0 或者180竖屏
Andriod0 或者180横屏
Andriod90或者-90竖屏


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

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


具体参照:

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


一个完整的例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title> 横竖屏测试网页 </title>
<script type="text/javascript">

// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

// 监听事件
window.addEventListener(orientationEvent, function() {
    var ua = navigator.userAgent;
    var deviceType="";

    //判断设备类型 

    if (ua.indexOf("iPad") > 0) {
       deviceType = "isIpad";
    } else if (ua.indexOf("Android") > 0) {
       deviceType = "isAndroid";
    } else {
       alert("既不是ipad,也不是安卓!");
       return;
    }
   

     // 判断横竖屏 

     if ("isIpad" == deviceType) {
       if (Math.abs(window.orientation) == 90) {
           alert("我是ipad的横屏");
       } else {
           alert("我是ipad的竖屏");
       }
    } else if ("isAndroid" == deviceType ) {
       if (Math.abs(window.orientation) != 90) {
           alert("我是安卓的横屏");
       } else {
           alert("我是安卓的竖屏");
       }
    }
}, false);
</script>
</head>


<body>
横竖屏测试网页
</body>
</html>  


  




  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值