如何用css和js移動端分別判斷手機橫豎屏的狀態

來源:互聯網
上載者:User
本篇文章給大家分享的是關於如何用css和js移動端分別判斷手機橫豎屏的狀態,內容很不錯,有需要的朋友可以參考一下,希望可以協助到大家。

禁用使用者自動縮放功能:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

判斷橫豎屏狀態有兩種方法:css判斷、js判斷

(一)、css判斷橫屏還是豎屏

1、寫在同一個css檔案中

@media screen and (orientation: portrait) {  /*豎屏 css*/} @media screen and (orientation: landscape) {  /*橫屏 css*/}

根據橫豎屏設定大小時,正常頁面尺寸常規書寫即可,橫屏樣式單獨設定。即只需在原有樣式基礎上添加橫屏樣式即可,

@media screen and (orientation: landscape) {  /*橫屏 css*/}當使用者橫屏時載入橫屏樣式,豎屏時取消橫屏樣式即載入預設樣式。

2、分開寫在兩個css中,根據橫豎屏引用不同樣式檔案:

根據橫豎屏引用不同樣式檔案

橫屏:

<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

豎屏:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">

備忘:css判斷橫豎屏是時時的可無縫銜接,即橫屏載入橫屏樣式,豎屏載入豎屏樣式,

(二)js判斷橫屏還是豎屏

//判斷手機橫豎屏狀態:    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {        if (window.orientation === 180 || window.orientation === 0) {             console.log("豎屏");            $(".codeIg_s").removeClass('vercreen');//取消橫屏樣式        }         if (window.orientation === 90 || window.orientation === -90 ){             console.log("橫屏");            $(".codeIg_s").addClass('vercreen');//添加橫屏樣式        }      }, false);

備忘:橫屏樣式在vercreen類名下修改原預設樣式,可正常使用,缺點是必須有橫豎屏的切換狀態才會觸發。

如果使用者預設是橫屏狀態時不會觸發橫屏條件判斷,只有使用者從橫屏轉為豎屏或者從豎屏轉為橫屏時才會觸發相應條件判斷。

沒有切換狀態時會不執行任何條件判斷,此處不如css判斷橫豎屏全面。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.