我正在 iPad (Safari浏览器)和 Samsung Tab 2 (默认浏览器)。 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);
}
在标签2中,警告为横向模式抛出'0'和'180',为纵向模式投放'90'和'-90'(只是iPad中相反的行为)。
这是iOS和Android的某种设计差异吗?什么是这个问题的常见解决方案?
答案 0 :(得分:3)
好的,这就是我的所作所为。我查询了用户代理信息,并检查该设备是否基于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%');
}
}
}
答案 1 :(得分:0)
如this问题的第二个答案中所述,您可以指定两个侦听器:一个用于方向更改,另一个用于调整屏幕宽度/高度值的大小。这样你就不必依赖旋转的值,因为它们在不同的设备中是不一致的。