# Detect mobile orientation on Web ### 情境 線上展覽攤位要能支援手機瀏覽器,在橫向螢幕的時候要跳出提示,建議使用者將手機打直閱覽。 ### 問題 使用 `onresize` 的方式監聽,Android 手機在虛擬鍵盤顯示的時候會觸發提示,無法做輸入的操作。 ### 解法 參考資料:[Dealing With Android’s Constant Browser Resizing](https://www.andreasnorman.com/dealing-androids-constant-browser-resizing/) 使用 `onorientationchange` 監聽,在電腦瀏覽器上不會觸發,iOS 上需要注意 window.onorientationchange 的 function 不得帶入參數,否則會失效。 Sample Code: ```htmlmixed= <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text" id="fname" name="fname"> <script> function isMobile() { const userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod']; var isMobile = true; if (macosPlatforms.indexOf(platform) !== -1) { isMobile = false; } else if (iosPlatforms.indexOf(platform) !== -1) { isMobile = true; } else if (windowsPlatforms.indexOf(platform) !== -1) { isMobile = false; } else if (/Android/.test(userAgent)) { isMobile = true; } else if (!os && /Linux/.test(platform)) { isMobile = false; } return false; } function isLandscape() { // !window.matchMedia('(min-aspect-ratio: 1/1)').matches // !window.matchMedia('(orientation: landscape)').matches // 以上在 Android / iOS 在第一次呼叫回傳如下:portrait = true, landscape = false return window.orientation !== 0; } function doSomethingWhenResize() { const isMobileLandscape = this.isMobile() && this.isLandscape(); if (isMobileLandscape) { alertWarning(); } } function alertWarning() { alert("Please keep device portrait to have best experience."); } // initial detect doSomethingWhenResize(); // orientation listener window.onorientationchange = () => { console.log("onorientationchange"); doSomethingWhenResize(); }; </script> </body> </html> ``` --- ###### tags: `javasctript` `detect-orientation` `web` `mobile`