首頁  >  文章  >  web前端  >  JavaScript 可以偵測 Android 手機在瀏覽器中的旋轉嗎?

JavaScript 可以偵測 Android 手機在瀏覽器中的旋轉嗎?

Susan Sarandon
Susan Sarandon原創
2024-10-26 08:42:02492瀏覽

 Can JavaScript Detect Android Phone Rotation in Browsers?

瀏覽器中基於Javascript的Android手機旋轉偵測

在Apple開發的Safari瀏覽器中,可以透過觀察orientationChange事件和評估視窗來監視螢幕方向的變化。方向。然而,這樣的功能可以在 Android 裝置上運行的瀏覽器中實現嗎?

對此的反應是細微差別的。標準網頁上的 JavaScript 執行確實可以偵測 Android 裝置中的螢幕旋轉。但是,不同裝置和瀏覽器的行為有所不同。

挑戰與建議方法

主要挑戰在於 Android 裝置之間的事件觸發行為不一致。 resize 和orientationChange 事件可能會以不同的頻率非同步觸發。為了增加這種複雜性,像 screen.width 和 window.orientation 這樣的值可能並不總是提供可預測的結果。因此,不建議僅依賴 screen.width,因為它在 iOS 旋轉期間保持不變。

最可靠的方法是同時偵聽 resize 和orientationChange 事件。使用 setInterval 函數透過定期輪詢來補充這一點可以增強可靠性,確保有效的方向值。

<code class="javascript">var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // Perform operations in response to orientation change
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// Android occasionally fails to trigger events for 180-degree rotations
setInterval(checkOrientation, 2000);</code>

設備特定結果

以下是觀察到的行為的摘要各種經過測試的設備:

Device Event Sequence orientation innerWidth screen.width
iPad 2 (Landscape) resize, orientationchange 90 1024 768
iPad 2 (Portrait) resize, orientationchange 0 768 768
iPhone 4 (Landscape) resize, orientationchange 90 480 320
iPhone 4 (Portrait) resize, orientationchange 0 320 320
Droid Phone (Landscape) orientationchange, resize 90 320 320
Droid Phone (Portrait) orientationchange, resize 0 569 569
Samsung Galaxy Tablet (Landscape) orientationchange, orientationchange, orientationchange, resize, orientationchange 90 400 400
Samsung Galaxy Tablet (Portrait) orientationchange, orientationchange, orientationchange, resize, orientationchange 0 683 683

以上是JavaScript 可以偵測 Android 手機在瀏覽器中的旋轉嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn