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

Dav*_*mas 20 javascript iphone jquery ipod-touch

出于好奇,我一直在使用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');
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

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

x:320,y:396

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

typ*_*ror 45

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

<body onorientationchange="updateOrientation();">
Run Code Online (Sandbox Code Playgroud)

由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.
Run Code Online (Sandbox Code Playgroud)


Paw*_*iel 22

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;

  }

});
Run Code Online (Sandbox Code Playgroud)

编辑:

虽然这对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 );
Run Code Online (Sandbox Code Playgroud)