检测iPad屏幕方向变化

33

如何使用 检测用户在 iPad 上将屏幕从垂直方向转换为水平方向或从水平方向转换为垂直方向?

4个回答

42

尝试

$(window).bind('orientationchange', function(event) {
  alert('new orientation:' + event.orientation);
});

5
在我测试的iPad 1上,事件对象没有方向属性,但是窗口对象有,所以我不得不使用orientation而不是event.orientation - tremby
非常感谢您的回答,@Karl-Bjørnar Øie。它以最佳方式解决了我的问题! - Anahit Ghazaryan
在pageLoad()或类似的函数中,该函数将在页面实际交互之前始终被调用。 - GreySage

20

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

jQuery:

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});

检查设备是否处于竖屏模式


function isPortrait() {
    return window.innerHeight > window.innerWidth;
}

2
那不应该是 console.log(event.orientation) 吗?(缺少 event) - David

12

在 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>

或者用于包含额外样式表的情况:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

这两个方法来自于:http://favo.asia/2010/07/detecting-ipad-orientation-using-javascript/。需要说明的是,该网址是在Google上搜索“detect ipad orientation javascript”时的第一个结果...


现在,这个问题已经排在谷歌的首位 :-) - Oliver
@Simon,你从哪里获取方向变量的? - MJB

-1
函数检测iPad方向(orientation){ 如果(方向== 0){ 警报('纵向模式,Home键在底部'); } else if(方向== 90){ 警报('横向模式,Home键在右边'); } else if(方向== -90){ 警报('横向模式,Home键在左边'); } else if(方向== 180){ 警报('纵向模式,Home键在顶部'); } }
window.onorientationchange = detectIPadOrientation;

2
我有什么遗漏吗?你从哪里获取方向变量? - Mark Anthony Uy
1
这只是Simon答案的复制粘贴吗? - GreySage
@GreySage 谁是Simon? - Fatih Acet
在您上面的答案中的用户。 - GreySage

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接