Javascript 如何在 iOS 上使用 Phonegap 正确检测方向变化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5284878/
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
How do I correctly detect orientation change using Phonegap on iOS?
提问by ajpalma
I found this orientation test code below looking for JQTouch reference material. This works correctly in the iOS simulator on mobile Safari but doesn't get handled correctly in Phonegap. My project is running into the same issue that is killing this test page. Is there a way to sense the orientation change using JavaScript in Phonegap?
我在下面找到了这个方向测试代码,以寻找 JQTouch 参考资料。这在移动 Safari 上的 iOS 模拟器中可以正常工作,但在 Phonegap 中无法正确处理。我的项目遇到了杀死这个测试页面的同样问题。有没有办法在 Phonegap 中使用 JavaScript 来感知方向变化?
window.onorientationchange = function() {
/*window.orientation returns a value that indicates whether iPhone is in portrait mode, landscape mode with the screen turned to the
left, or landscape mode with the screen turned to the right. */
var orientation = window.orientation;
switch (orientation) {
case 0:
/* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration
in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
document.body.setAttribute("class", "portrait");
/* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events" */
document.getElementById("currentOrientation").innerHTML = "Now in portrait orientation (Home button on the bottom).";
break;
case 90:
/* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the
body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
document.body.setAttribute("class", "landscape");
document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the left (Home button to the right).";
break;
case -90:
/* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the
body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
document.body.setAttribute("class", "landscape");
document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the right (Home button to the left).";
break;
}
}
回答by Benny Neugebauer
This is what I do:
这就是我所做的:
function doOnOrientationChange() {
switch(window.orientation) {
case -90: case 90:
alert('landscape');
break;
default:
alert('portrait');
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// Initial execution if needed
doOnOrientationChange();
Update May 2019:window.orientation
is a deprecated feature and not supported by most browsers according to MDN. The orientationchange
event is associated with window.orientationand therefore should probably not be used.
2019 年 5 月更新:根据 MDNwindow.orientation
是一项已弃用的功能,大多数浏览器都不支持。该事件与 window.orientation 相关联,因此可能不应使用。orientationchange
回答by hndcrftd
I use window.onresize = function(){ checkOrientation(); }
And in checkOrientation you can employ window.orientation or body width checking
but the idea is, the "window.onresize" is the most cross browser method, at least with the majority of the mobile and desktop browsers that I've had an opportunity to test with.
我使用window.onresize = function(){ checkOrientation(); }
并且在 checkOrientation 中你可以使用 window.orientation 或 body 宽度检查,但这个想法是,“window.onresize”是最跨浏览器的方法,至少对于我拥有的大多数移动和桌面浏览器测试的机会。
回答by Alyssa Reyes
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
}
回答by avoision
I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:
我对 iOS 和 Phonegap 也很陌生,但我能够通过添加一个 eventListener 来做到这一点。我做了同样的事情(使用您引用的示例),但无法使其正常工作。但这似乎奏效了:
// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation);
function updateOrientation(e) {
switch (e.orientation)
{
case 0:
// Do your thing
break;
case -90:
// Do your thing
break;
case 90:
// Do your thing
break;
default:
break;
}
}
You may have some luck searching the PhoneGap Google Group for the term "orientation".
您可能会在 PhoneGap Google Group 中搜索“orientation”这个词。
One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.
我读到的一个关于如何检测方向的例子是 Pie Guy: ( game, js file)。它类似于您发布的代码,但就像您一样......我无法让它工作。
One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.
一个警告: eventListener 为我工作,但我不确定这是否是一种过于密集的方法。到目前为止,这是对我有用的唯一方法,但我不知道是否有更好、更简化的方法。
UPDATEfixed the code above, it works now
UPDATE修复了上面的代码,现在可以使用了
回答by oncode
While working with the orientationchange
event, I needed a timeout to get the correct dimensions of the elements in the page, but matchMedia worked fine. My final code:
在处理orientationchange
事件时,我需要超时才能获得页面中元素的正确尺寸,但 matchMedia 工作正常。我的最终代码:
var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;
if (typeof(matchMedia) !== 'undefined') {
// use matchMedia function to detect orientationchange
window.matchMedia('(orientation: portrait)').addListener(function() {
// your code ...
});
} else {
// use orientationchange event with timeout (fires to early)
$(window).on('orientationchange', function() {
window.setTimeout(function() {
// your code ...
}, 300)
});
}
回答by WebWanderer
I believe that the correct answer has already been posted and accepted, yet there is an issue that I have experienced myself and that some others have mentioned here.
我相信正确的答案已经发布并被接受,但是我自己也遇到过一个问题,其他一些人也在这里提到过。
On certain platforms, various properties such as window dimensions (window.innerWidth
, window.innerHeight
) and the window.orientation
property will not be updated by the time that the event "orientationchange"
has fired. Many times, the property window.orientation
is undefined
for a few milliseconds after the firing of "orientationchange"
(at least it is in Chrome on iOS).
在某些平台上,各种属性(例如窗口尺寸 ( window.innerWidth
, window.innerHeight
) 和window.orientation
属性)在事件"orientationchange"
触发时不会更新。很多时候,物业window.orientation
是undefined
为点火之后的几毫秒"orientationchange"
(至少是在iOS版Chrome)。
The best way that I found to handle this issue was:
我发现处理此问题的最佳方法是:
var handleOrientationChange = (function() {
var struct = function(){
struct.parse();
};
struct.showPortraitView = function(){
alert("Portrait Orientation: " + window.orientation);
};
struct.showLandscapeView = function(){
alert("Landscape Orientation: " + window.orientation);
};
struct.parse = function(){
switch(window.orientation){
case 0:
//Portrait Orientation
this.showPortraitView();
break;
default:
//Landscape Orientation
if(!parseInt(window.orientation)
|| window.orientation === this.lastOrientation)
setTimeout(this, 10);
else
{
this.lastOrientation = window.orientation;
this.showLandscapeView();
}
break;
}
};
struct.lastOrientation = window.orientation;
return struct;
})();
window.addEventListener("orientationchange", handleOrientationChange, false);
I am checking to see if the orientation is either undefined or if the orientation is equal to the last orientation detected. If either is true, I wait ten milliseconds and then parse the orientation again. If the orientation is a proper value, I call the showXOrientation
functions. If the orientation is invalid, I continue to loop my checking function, waiting ten milliseconds each time, until it is valid.
我正在检查方向是否未定义或方向是否等于检测到的最后一个方向。如果任一为真,我等待十毫秒,然后再次解析方向。如果方向是一个合适的值,我调用showXOrientation
函数。如果方向无效,我继续循环我的检查函数,每次等待十毫秒,直到它有效。
Now, I would make a JSFiddle for this, as I usually did, but JSFiddle has not been working for me and my support bug for it was closed as no one else is reporting the same problem. If anyone else wants to turn this into a JSFiddle, please go ahead.
现在,我会像往常一样为此创建一个 JSFiddle,但 JSFiddle 一直没有为我工作,我的支持错误已关闭,因为没有其他人报告同样的问题。如果其他人想把它变成 JSFiddle,请继续。
Thanks! I hope this helps!
谢谢!我希望这有帮助!
回答by Raul Gomez
here is what i did:
这是我所做的:
window.addEventListener('orientationchange', doOnOrientationChange);
function doOnOrientationChange()
{
if (screen.height > screen.width) {
console.log('portrait');
} else {
console.log('landscape');
}
}
回答by Luigi
I've found this code to detect if the device is in landscape orientation and in this case add a splash page saying "change orientation to see the site". It's working on iOS, android and windows phones. I think that this is very useful since it's quite elegant and avoid to set a landscape view for the mobile site. The code is working very well. The only thing not completely satisfying is that if someone load the page being in landscape view the splash page doesn't appears.
我发现这个代码可以检测设备是否处于横向,在这种情况下添加一个启动页面,上面写着“改变方向以查看站点”。它适用于 iOS、Android 和 Windows 手机。我认为这非常有用,因为它非常优雅并且避免为移动站点设置横向视图。该代码运行良好。唯一不完全令人满意的是,如果有人在横向视图中加载页面,则不会出现启动页面。
<script>
(function() {
'use strict';
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
}
};
if (isMobile.any()) {
doOnOrientationChange();
window.addEventListener('resize', doOnOrientationChange, 'false');
}
function doOnOrientationChange() {
var a = document.getElementById('alert');
var b = document.body;
var w = b.offsetWidth;
var h = b.offsetHeight;
(w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
}
})();
</script>
And the HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>
和 HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>
回答by M Fauzi Riozi
if (window.DeviceOrientationEvent) {
// Listen for orientation changes
window.addEventListener("orientationchange", orientationChangeHandler);
function orientationChangeHandler(evt) {
// Announce the new orientation number
// alert(screen.orientation);
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
if (mql.matches) //true
}
}
回答by Alexey Grinko
Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:
虽然这个问题只涉及 PhoneGap 和 iOS 的使用,虽然已经有人回答了,但我可以对 2019 年用 JS 检测屏幕方向这个更广泛的问题补充几点:
window.orientation
property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation -screen.orientation
. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two:const angle = screen.orientation ? screen.orientation.angle : window.orientation
.As @benallansmith mentioned in his comment,
window.onorientationchange
event is fired beforewindow.onresize
, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.There is a Cordova Screen Orientation Pluginfor supporting older mobile browsers, but I believe there is no need in using it nowadays.
There was also a
screen.onorientationchange
event, but it is deprecatedand should not be used. Added just for completeness of the answer.
window.orientation
属性已弃用,Android 浏览器不支持。有一个较新的属性可提供有关方向的更多信息 -screen.orientation
。但它仍然是实验性的,不受iOS Safari支持。因此,要获得最佳结果,您可能需要结合使用两者:const angle = screen.orientation ? screen.orientation.angle : window.orientation
.正如@benallansmith 在他的评论中提到的,
window.onorientationchange
事件是在之前触发的window.onresize
,因此除非在orientationchange 事件之后添加一些延迟,否则您将无法获得屏幕的实际尺寸。有一个Cordova Screen Orientation Plugin用于支持旧的移动浏览器,但我相信现在没有必要使用它。
还有一个
screen.onorientationchange
事件,但它已被弃用,不应使用。添加只是为了答案的完整性。
In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize
event to avoid dealing with delays between orientationchange
event and actualizing window dimensions:
在我的用例中,我不太关心实际的方向,而是关心窗口的实际宽度和高度,这显然会随着方向而变化。所以我使用resize
事件来避免处理orientationchange
事件和实现窗口尺寸之间的延迟:
window.addEventListener('resize', () => {
console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});
Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.
注 1:我在这里使用了 EcmaScript 6 语法,如果需要,请确保将其编译为 ES5。
Note 2: window.onresize
event is also fired when virtual keyboard is toggled, not only when orientation changes.
注 2:切换虚拟键盘时window.onresize
也会触发事件,而不仅仅是在方向更改时。