检测iPad方向变化

lol*_*ola 30 javascript iphone jquery screen-orientation ipad

当用户将iPad从垂直位置转换为水平位置或从水平位置转换为垂直位置时,如何使用进行检测?

Kar*_*Øie 41

尝试

$(window).bind('orientationchange', function(event) {
  alert('new orientation:' + event.orientation);
});
Run Code Online (Sandbox Code Playgroud)

  • 在Ipad 1上我测试的事件对象没有orientation属性,但是window对象确实如此,所以我不得不使用`orientation`而不是`event.orientation`. (5认同)

mar*_*nas 17

您可以使用以下代码检测方向更改事件:

jQuery的:

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});
Run Code Online (Sandbox Code Playgroud)

检查设备是否处于纵向模式

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}
Run Code Online (Sandbox Code Playgroud)

  • 不应该是`console.log(event.orientation)`?(事件缺失) (2认同)

Sim*_*mon 13

在Javascript中:

<button onclick="detectIPadOrientation();">What's my Orientation?</button>

<script type="text/javascript">
 window.onorientationchange = detectIPadOrientation;
 function detectIPadOrientation () {

    if ( orientation == 0 ) {
     alert ('Portrait Mode, Home Button bottom');
    }
    else if ( orientation == 90 ) {
     alert ('Landscape Mode, Home Button right');
    }
    else if ( orientation == -90 ) {
     alert ('Landscape Mode, Home Button left');
    }
    else if ( orientation == 180 ) {
     alert ('Portrait Mode, Home Button top');
    }
 }
</script>
Run Code Online (Sandbox Code Playgroud)

或者包括其他样式表:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">
Run Code Online (Sandbox Code Playgroud)

两者都取自:http://favo.asia/2010/07/detecting-ipad-orientation-using-javascript/,其中,FYI,是Google上第一个'检测ipad方向javascript'的结果......