网站首页学无止境JS
iPad Android系统下,平板设备判断横竖屏,以及横竖屏变化之
发布时间:2015-04-15 11:11:35编辑:songlin阅读(113)
- // 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);
- >
- <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>
平板开发中,经常需要用到设备判断横屏竖屏,以及屏幕发生横竖变化时候所触发的一些事件。
基本上使用下面的js就可以了。
无论是ipad还是安卓:
可以在function里面实装切换后的事件,比如横竖屏不同,画面的布局设计,css使用不同等等。
※你可以使用window.orientation来判断切换之后到底是横屏还是竖屏。
但是: 关于上面的代码,有几项是需要注意的。
1, window.orientation
经过测试,在ipad,和andriod系统上面,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
一个完整的例子: