摘要:在做移動端頁面的時候經(jīng)常會遇到需要判斷橫屏還是豎屏。下面將目前已知的通過HTML,CSS,JS三種判斷方法記錄下來,方便以后翻閱。1、通過在html中分別引用橫屏和豎屏的樣式:<link rel="stylesheet" media="all and (orientation:portrait)" hr
在做移動端頁面的時候經(jīng)常會遇到需要判斷橫屏還是豎屏。下面將目前已知的通過HTML,CSS,JS三種判斷方法記錄下來,方便以后翻閱。
1、通過在html中分別引用橫屏和豎屏的樣式:
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow" > //引用豎屏的CSS <link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow" > //引用橫屏的CSS
2、CSS中通過媒體查詢的方法來判斷:
@media (orientation: portrait ){ //豎屏CSS } @media ( orientation: landscape ){ //橫屏CSS }
3、js判斷是否為橫屏豎屏:
window.addEventListener("onorientationchange" in window ? orientationchange" : "resize", function() { if (window.orientation === 180 || window.orientation === 0) { alert('豎屏狀態(tài)!'); } if (window.orientation === 90 || window.orientation === -90 ){ alert('橫屏狀態(tài)!'); } }, false);
只要用戶改變了設(shè)備的查看模式,就會觸發(fā)onorientationchange事件。
orientation有4個值:0,90,-90,180
值為0和180的時候為豎屏(180為倒過來的豎屏);
90和-90時為橫屏(-90為倒過來的豎屏模式);
更多關(guān)于判斷橫屏豎屏方法請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!