iPad Android系統下,平板設備判斷橫豎屏,以及橫豎屏變化之後的事件觸發(html + javascript)

平板開發中,經常需要用到設備判斷橫屏豎屏,以及屏幕發生橫豎變化時候所觸發的一些事件。
基本上使用下面的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>    


發佈了57 篇原創文章 · 獲贊 6 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章