本文分享一個以 JavaScript 依 iPhone 螢幕旋轉方向動態載入不同樣式表的做法,讓版面能適應橫向與直向的切換,供大家參考。
<script type="text/javascript">
function orient() {
switch (window.orientation) {
case 0:
document.getElementById("orient_css").href = "css/iphone_portrait.css";
break;
case -90:
document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
case 90:
document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
}
}
window.onload = orient();
</script>透過 window.orientation 取得螢幕方向,再動態替換 link 標籤的 href,就能在直向與橫向時套用不同的樣式,達到自適應的效果。