23

有人可以让我知道jquery mobile在电话间隙中进行方向更改事件的正确代码吗?我在哪里以及如何实现这个orientationChange函数?

4

4 回答 4

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

然后在_orientationHandler函数中,有类似的东西:

if(event.orientation){
      if(event.orientation == 'portrait'){
                  //do something
      }
      else if(event.orientation == 'landscape') {
                    //do something
      }
}
于 2012-04-05T08:40:20.750 回答
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 不起作用,您可以在绑定函数的 event 参数中添加 resize 事件。因为改变方向也会触发调整大小事件。

于 2012-04-05T09:35:47.680 回答
1

我在我的移动模板中使用它,因为在 iOS 7 Safari 上没有触发orientationchange 事件:

    // 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
于 2014-06-18T10:54:11.053 回答
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. });

第 2 行占用任何非 Safari 浏览器的 resize 事件,因为其他设备中的其他浏览器占用 resize 事件比方向更改事件更一致。 http://www.quirksmode.org/m/table.html

第 5 行执行超时检查,因为某些 android 原生浏览器不会立即占用新宽度。

第 6 行 要发生方向变化,新旧高度和宽度差的乘积应该是负数。

于 2013-10-02T14:26:43.277 回答