在移動端開發中,經常需要判斷設備是橫屏還是豎屏,進而執行不同操作,比如分別載入不同樣式、橫屏顯示某些內容而豎屏顯示另一些內容等等。
移動設備提供了兩個好用的工具:一個屬性和一個事件。
window.orientation 是 window 物件上的屬性,有三種值:0 為豎屏(portrait);90 為向左旋轉的橫屏(landscape);-90 為向右旋轉的橫屏;180 則是設備上下顛倒但仍是豎屏。
orientationchange 是一個事件,在設備旋轉時觸發,類似 PC 上的 resize 事件。兩者搭配使用,就能輕鬆掌握設備的橫豎屏狀態。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js 檢測移動設備橫豎屏</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<h2>js 檢測移動設備橫豎屏</h2>
<div id="screenhovertree" style="height:100px;width:320px;border:1px solid silver"></div>
<script>
function orienthovertree() {
if (window.orientation == 0 || window.orientation == 180) {
// 豎屏
$("#screenhovertree").text("豎屏");
} else if (window.orientation == 90 || window.orientation == -90) {
// 橫屏
$("#screenhovertree").text("橫屏");
}
}
// 頁面載入時調用
$(function () {
orienthovertree();
});
// 屏幕方向變化時調用
window.addEventListener("orientationchange", function () {
orienthovertree();
}, false);
</script>
</body>
</html>
透過 window.orientation 取值判斷方向,並監聽 orientationchange 事件即時響應旋轉,就能實現橫豎屏的自動檢測。