请问有谁能告诉我在PhoneGap中使用jQuery Mobile的正确方向更改事件代码? 我应该在哪里以及如何实施这个orientationChange函数?
$(window).bind('orientationchange', _orientationHandler);
然后在_orientationHandler
函数中,加入类似以下的内容:
if(event.orientation){
if(event.orientation == 'portrait'){
//do something
}
else if(event.orientation == 'landscape') {
//do something
}
}
$(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 事件。
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行为了进行方向更改,旧高度和宽度的差异乘积应该是负数。
我在我的移动模板中使用这个,因为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
on
事件处理程序:$(window).on("orientationchange", function(event) { }
。这将监听窗口方向变化事件并执行相应的函数。 - Dylan Valade