您的位置:首页 > 移动开发 > Android开发

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

2012-08-31 21:27 525 查看
平板开发中,经常需要用到设备判断横屏竖屏,以及屏幕发生横竖变化时候所触发的一些事件。

基本上使用下面的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值参考:

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

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

<!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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐