js / jQuery可以确定iPhone的方向吗?

出于好奇,我一直在使用jQuery来确定浏览器的屏幕大小,我想到屏幕大小可以用来确定访问者是否使用iPhone / iTouch来查看网站。

所以我使用以下来测试这个:

$(document).ready( function() { var screenX = screen.width, screenY = screen.height; alert("X: " + screenX + " Y: " + screenY); if (screenX == 320 && screenY == 396) { $('div#wrap').css('background-color','#f00'); } else if (screenY == 320 && screenX == 396) { $('div#wrap').css('background-color','#0f0'); } } ); 

在通过iPhone查看页面时,我注意到尺寸始终如一(无论方向如何):

x:320,y:396

这与方向无关。 到目前为止,我还没有尝试使用onChange事件来检测更改(主要是因为我在jQuery上仍然很新),但我想知道是否有办法通过jQuery或普通的javascript确定iPhone / iTouch的定位?

window.orientation会给你一个表示旋转的整数。 您可以通过向正文添加事件来侦听方向更改:

  

由OP编辑,只是因为链接在某个时刻死亡或被移动的可能性很大……

 Value | Description -------+------------------------------------------------------------------------------- 0 | Portrait orientation. This is the default value. -90 | Landscape orientation with the screen turned clockwise. 90 | Landscape orientation with the screen turned counterclockwise. 180 | Portrait orientation with the screen turned upside down. This value is currently not supported on iPhone. 
 jQuery(window).bind('orientationchange', function(e) { switch ( window.orientation ) { case 0: alert('portrait mode'); break; case 90: alert('landscape mode screen turned to the left'); break; case -90: alert('landscape mode screen turned to the right'); break; } }); 

编辑:

虽然这对iPhone来说没问题,但在其他设备上可能无法正常工作。

我想在http://phoboslab.org/log/2012/06/x-type-making-of中添加一些我发现的信息

他的例子是更多跨浏览器/设备兼容。

Mobile Safari和Chrome都支持orientationchange事件,这使得这很容易。 但是,我们不能依赖window.orientation,它以度数(0,90,180或270)报告旋转,因为有些设备报告0°用于纵向模式,而其他设备报告0°用于横向。 多方便啊!

解决方案是检查窗口高度是否大于宽度 – 如果是这样,我们显然处于纵向模式! 但由于这太简单了,Chrome浏览器为我们提供了另一项挑战:它只在触发orientationchange事件后更新窗口尺寸。 所以我们会监听orientationchange并调整事件大小。 叹。

 var wasPortrait = -1; var checkOrientation = function() { var isPortrait = (window.innerHeight > window.innerWidth); if( isPortrait === wasPortrait ) { return; // Nothing to do here } wasPortrait = isPortrait; // Do your stuff... }; window.addEventListener( 'orientationchange', checkOrientation, false ); window.addEventListener( 'resize', checkOrientation, false ); 

请参阅https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW1的 “处理方向事件”

仅限移动电话/平板电脑

 switch ( window.orientation ) { case 0: alert('portrait mode'); break; case 90: alert('landscape mode screen turned to the left'); break; case -90: alert('landscape mode screen turned to the right'); break; } 

这仅适用于手机和平板电脑 ! 平板电脑的基本方向(案例0)不同。 三星案例0是风景,iPad案例0是肖像。

我尝试使用.height()和.width()进行平板电脑跨平台的类似方法,然后比较哪个更大。 它适用于iOS5(在Ipad2上测试)和BlackBerry Rim,但显然不适用于Android(3.2和4.0.3)。 在Android上第一次加载网站时,它给我正确的高度和宽度,但随后改变屏幕方向,它总是落后一步。
防爆。 使用从纵向模式开始的尺寸800×1200:
h:1200 w:800(肖像)
h:1200 w:800(风景)
h:800 w:1200(肖像)
h:1200 w:800(风景)

看着我用CSS3绊倒了这个解决方案:
如何使用javascript有条件地像CSS3媒体查询,方向?
这可能比调整Js解决方案更好。