javascript window.orientation 在 iOS 和 Android 中返回不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14019939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.orientation returns different values in iOS and Android
提问by Sayan
I am testing my Web Application on iPad(Safari browser)and Samsung Tab 2(Default browser). The window.orientationchangereturns different values in both the devices.
我正在iPad (Safari 浏览器)和Samsung Tab 2 (默认浏览器)上测试我的 Web 应用程序。该window.orientationchange返回两个设备不同的值。
$(document).ready(function() {
window.addEventListener("orientationchange", centerLoginBox);
window.addEventListener("load", centerLoginBox);
});
function centerLoginBox() {
if (window.orientation == 90 || window.orientation == -90) { //Landscape Mode
$('#loginbox').css('margin-top', '20%');
alert(window.orientation);
}
else if (window.orientation == 0 || window.orientation == 180) { //Portrait Mode
$('#loginbox').css('margin-top', '40%');
alert(window.orientation);
}
In Tab 2 the alert throws '0' and '180' for landscapemode and the values '90' and '-90' for portraitmode(just the opposite behavior in iPad).
在 Tab 2 中,横向模式的警报抛出“0”和“180 ”,纵向模式的值“90”和“-90” (与 iPad 中的行为相反)。
Is this some kind of design difference in iOS and Android? What could be a common solution for this issue?
这是 iOS 和 Android 中的某种设计差异吗?这个问题的通用解决方案是什么?
采纳答案by Sayan
Ok, this is what I did. I queried for the User Agent information and checked if the device was Android based. If so, change the conditions of window.orientationfor both Portrait and Landscape mode.
好的,这就是我所做的。我查询了用户代理信息并检查了该设备是否基于 Android。如果是这样,请更改纵向和横向模式的window.orientation条件。
CODE
代码
function centerLoginBox() {
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; // Detect Android devices
if (isAndroid) {
//window.orientation is different for iOS and Android
if (window.orientation == 0 || window.orientation == 180) { //Landscape Mode
$('#loginbox').css('margin-top', '20%');
}
else if (window.orientation == 90 || window.orientation == -90) { //Portrait Mode
$('#loginbox').css('margin-top', '40%');
}
}
else {
if (window.orientation == 90 || window.orientation == -90) { //Landscape Mode
$('#loginbox').css('margin-top', '20%');
}
else if (window.orientation == 0 || window.orientation == 180) { //Portrait Mode
$('#loginbox').css('margin-top', '40%');
}
}
}
回答by Androidz
As mentioned in the second answer in thisquestion you can assign two listeners: one for the orientation change and one for the resize of the screen width/height values. this way you dont have to rely on the values of the rotation because they are inconsistent in different devices.
如本问题的第二个答案所述,您可以分配两个侦听器:一个用于方向更改,另一个用于调整屏幕宽度/高度值的大小。这样你就不必依赖旋转的值,因为它们在不同的设备中是不一致的。