JavaScript實現(xiàn)移動端橫豎屏檢測
本文實例為大家分享了JavaScript實現(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的時候為豎屏(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),提示用戶 “為了更好的觀看體驗,請在豎屏下瀏覽”,否則不提示
<!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>為了更好的觀看體驗,請在豎屏下瀏覽</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)文章
JavaScript實現(xiàn)時間格式的切割與轉(zhuǎn)換
這篇文章主要為大家詳細(xì)介紹了使用JavaScript實現(xiàn)時間格式的切割與轉(zhuǎn)換的相關(guān)知識,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下2024-04-04
JavaScript forEach 方法跳出循環(huán)的操作方法
這篇文章主要介紹了JavaScript forEach 方法跳出循環(huán)的操作方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01
js實現(xiàn)權(quán)限樹的更新權(quán)限時的全選全消功能
上一篇發(fā)了添加權(quán)限時的權(quán)限樹JS源碼,下面把更新時的也發(fā)給大家借鑒一下,因為更新時候牽扯到判斷已有權(quán)限等,所以,還要麻煩一些。2009-02-02
Kindeditor單獨(dú)調(diào)用單圖上傳增加預(yù)覽功能的實例
下面小編就為大家?guī)硪黄狵indeditor單獨(dú)調(diào)用單圖上傳增加預(yù)覽功能的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07

