在做移動端頁面的時候經(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為倒過來的豎屏模式);
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!
新聞熱點
疑難解答