首页  >  文章  >  web前端  >  如何使用 JavaScript 在浏览器中可靠地检测 Android 手机旋转?

如何使用 JavaScript 在浏览器中可靠地检测 Android 手机旋转?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-26 08:30:30829浏览

How Can You Reliably Detect Android Phone Rotation in Browsers Using JavaScript?

使用 JavaScript 检测浏览器中的 Android 手机旋转

虽然可以使用 JavaScript 检测 iPhone 上 Safari 中的屏幕方向和变化,但在 Android 手机上也可行吗?

Android 上的响应式旋转检测

在 Android 手机中,由于设备和浏览器之间的行为不同,使用 JavaScript 进行旋转检测是一件复杂的事情。仅仅依赖调整大小或方向更改事件是不可靠的。

可靠的方法

推荐的方法包括监视调整大小和方向更改事件,通过轮询间隔持续检查方向更新.

<code class="javascript">var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

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

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);</code>

设备特定行为

设备对方向变化的响应差异很大。以下是通过测试四种不同设备获得的事件排序和值的表格:

Device Events Fired orientation innerWidth screen.width
iPad 2 (to landscape) resize, orientationchange 0 1024 768
iPad 2 (to portrait) resize, orientationchange 90 768 768
iPhone 4 (to landscape) resize, orientationchange 0 480 320
iPhone 4 (to portrait) resize, orientationchange 90 320 320
Droid phone (to landscape) orientationchange, resize 90 320 320
Droid phone (to portrait) resize, orientationchange, resize 0 569 569
Samsung Galaxy Tablet (to landscape) orientationchange, orientationchange, resize 0 400 400
Samsung Galaxy Tablet (to portrait) orientationchange, orientationchange, orientationchange, resize 90 683 683

结论

虽然 iOS 和 Android 设备之间方向更改的事件处理可能有所不同,但采用推荐的方法可确保使用 JavaScript 在 Android 手机上进行可靠的方向检测。

以上是如何使用 JavaScript 在浏览器中可靠地检测 Android 手机旋转?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn