欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實(shí)現(xiàn)移動端橫豎屏檢測

 更新時間:2022年07月20日 14:42:11   作者:黎&&軒  
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)移動端橫豎屏檢測,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了JavaScript實(shí)現(xiàn)移動端橫豎屏檢測的具體代碼,供大家參考,具體內(nèi)容如下

一、HTML方法檢測

在html中分別引用橫屏和豎屏樣式

<!-- 引用豎屏的CSS文件 portrait.css -->
? <link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow"  >
??
? <!-- 引用橫屏的CSS文件 landscape.css -->
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow"  >

二、CSS方法檢測

css中通過媒體查詢方法來判斷是橫屏還是豎屏

/* 豎屏 */
? ? @media screen and (orientation:portrait) {
? ? ? /* 這里寫豎屏樣式 */
? ? }
?
? ? /* 橫屏 */
? ? @media screen and (orientation:landscape) {
? ? ? /* 這里寫橫屏樣式 */
}

三、JS方法檢測

【1】orientationChange事件

蘋果公司為移動 Safari中添加了 orientationchange 事件,orientationchange 事件在設(shè)備的縱橫方向改變時觸發(fā)

window.addEventListener("orientationchange",function(){
? ? ? ? alert(window.orientation);
? ? }); ?

【2】orientation屬性

window.orientation 獲取手機(jī)的橫豎的狀態(tài),window.orientation 屬性中有 4個值:0和180的時候?yàn)樨Q屏(180為倒過來的豎屏),90和-90時為橫屏(-90為倒過來的橫屏)

0 表示肖像模式,90 表示向左旋轉(zhuǎn)的橫向模式(“主屏幕”按鈕在右側(cè)),-90 表示向右旋轉(zhuǎn)的橫向模 式(“主屏幕”按鈕在左側(cè)),180 表示 iPhone頭朝下;但這種模式至今 尚未得到支持。如圖展示了 window.orientation 的每個值的含義。

【3】案例

檢測用戶當(dāng)前手機(jī)橫豎屏狀態(tài),如果處于橫屏狀態(tài),提示用戶 “為了更好的觀看體驗(yàn),請在豎屏下瀏覽”,否則不提示

<!DOCTYPE html>
<html lang="en">
?
<head>
? <meta charset="UTF-8">
? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? <title>Document</title>
? <style>
? ? #box {
? ? ? position: fixed;
? ? ? box-sizing: border-box;
? ? ? padding: 50px;
? ? ? display: none;
? ? ? left: 0;
? ? ? top: 0;
? ? ? width: 100%;
? ? ? height: 100%;
? ? ? background: rgba(0, 0, 0, .5);
? ? }
?
? ? #box span {
? ? ? margin: auto;
? ? ? font: 20px/40px "宋體";
? ? ? color: #fff;
? ? ? text-align: center;
? ? }
? </style>
</head>
?
<body>
? <div id="box"><span>為了更好的觀看體驗(yàn),請在豎屏下瀏覽</span></div>
? <script>
? ? window.addEventListener("orientationchange", toOrientation);
? ? function toOrientation() {
? ? ? let box = document.querySelector("#box");
? ? ? if (window.orientation == 90 || window.orientation == -90) {
? ? ? ? // 橫屏-顯示提示
? ? ? ? box.style.display = "flex";
? ? ? } else {
? ? ? ? // 橫屏-隱藏提示
? ? ? ? box.style.display = "none";
? ? ? }
? ? }
? </script>
</body>
?
</html>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論