jQuery Mobile在PhoneGap中实现屏幕方向变化事件

23
请问有谁能告诉我在PhoneGap中使用jQuery Mobile的正确方向更改事件代码? 我应该在哪里以及如何实施这个orientationChange函数?
4个回答

45
$(window).bind('orientationchange', _orientationHandler);

然后在_orientationHandler函数中,加入类似以下的内容:

if(event.orientation){
      if(event.orientation == 'portrait'){
                  //do something
      }
      else if(event.orientation == 'landscape') {
                    //do something
      }
}

3
当屏幕方向改变时,您想要做什么。 - ghostCoder
如果您查看SplitView代码,您可以看到它在纵向模式下隐藏一个面板的操作。 - ghostCoder
是的。添加CSS类...等等。 - ghostCoder
4
当前的jQuery版本建议使用on事件处理程序:$(window).on("orientationchange", function(event) { }。这将监听窗口方向变化事件并执行相应的函数。 - Dylan Valade

12
$(window).bind( 'orientationchange', function(e){
    if ($.event.special.orientationchange.orientation() == "portrait") {
        //Do whatever in portrait mode
    } else {
        //Do Whatever in landscape mode
    }
});

如果你要针对 iOS 并且 orientationchange 无法生效时,可以在绑定函数的事件参数中添加 resize 事件。因为改变方向也会触发 resize 事件。


请告诉我在“//竖屏模式下执行任何操作”和“//横屏模式下执行任何操作”中我应该做什么,这里我有些困惑...? - Nishant
3
无论您在手机横屏模式还是竖屏模式下的意图是什么。 - MauganRa

1
以下代码应该适用于所有浏览器来检测方向变化。它不使用jQuery移动事件,但似乎适用于大多数设备。
1. var isIOS = /safari/g.test(navigator.userAgent.toLowerCase());
2. var ev = isIOS ? 'orientationchange' : 'resize'; 
3. var diff = (window.innerWidth-window.innerHeight);
4. $(window).bind(ev,function(){
5.     setTimeout(function(){
6.         if(diff*((window.innerWidth-window.innerHeight)) < 0)
7.             orientationChanged();
8.     },500);
9. });

对于任何非Safari浏览器,第2行占用了调整大小事件,因为其他设备中的其他浏览器更加一致地占用调整大小事件。 http://www.quirksmode.org/m/table.html

第5行在超时中执行检查,因为某些Android本机浏览器不会立即占用新宽度。

第6行为了进行方向更改,旧高度和宽度的差异乘积应该是负数。


1

我在我的移动模板中使用这个,因为iOS 7 Safari上的方向改变事件没有被触发:

    // ORIENTATION CHANGE TRICK
    var _orientation = window.matchMedia("(orientation: portrait)");
    _orientation.addListener(function(m) {
        if (m.matches) {
            // Changed to portrait
            $('html').removeClass('orientation-landscape').addClass('orientation-portrait');
        } else {
            // Changed to landscape
            $('html').removeClass('orientation-portrait').addClass('orientation-landscape');
        }
    });
    //  (event is not triggered in some browsers)
    $(window).on('orientationchange', function(e) {
        if (e.orientation) {
            if (e.orientation == 'portrait') {
                $('html').removeClass('orientation-landscape').addClass('orientation-portrait');
            } else if (e.orientation == 'landscape') {
                $('html').removeClass('orientation-portrait').addClass('orientation-landscape');
            }
        }
    }).trigger('orientationchange');
    // END TRICK

使用此脚本,您可以更轻松地编写基于方向的 CSS 规则。 - itsjavi
非常有用。谢谢。 - Giuseppe

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