Fancybox – 用于检测移动方向的javascript,如果是肖像,则启动建议弹出窗口

我有fancybox弹出窗口启动OK,但现在只响应:

if (window.innerWidth < 400 && window.innerHeight < 600) 

请参见此处的示例: www.casedasole.it/testing/popup.html

如果以低于400px的宽度重新加载页面,则会弹出弹出窗口。

但我需要的是将“if”更改为表示移动设备处于纵向模式的任何内容。 然后弹出窗口会说:“这个网站在风景中看起来更好”。 我发现了对orientationchange事件的引用,但是没有任何东西可用于检测移动设备是否处于纵向状态,如果是,则启动弹出窗口。 现在的代码是:

 if (window.innerWidth < 400 && window.innerHeight < 600) {$.fancybox.open([ { href : 'http://sofzh.miximages.com/jquery/jarac.jpg' } ], { padding : 0 } );} 

jsFiddle Demo

你应该做的只是检查窗口的宽度和高度。 如果宽度>高于高度,则它是横向的。 如果高度超过宽度则为纵向。

 if (window.innerWidth < window.innerHeight)//portait if (window.innerWidth > window.innerHeight)//landscape 

编辑

应该是

 var isPortrait = window.innerWidth < window.innerHeight; if( isPortrait ) { $.fancybox.open([ { href : 'http://sofzh.miximages.com/jquery/jarac.jpg' } ], { padding : 0 } ); } 

我用来比较widthheight ,不仅适用于移动设备,也适用于桌面浏览器,但如果你真的想要过滤移动设备,那么请比较function。

这就是我通常做的事情:

 // detect mobile devices that support touch screen feature // including windows mobile devices var isTouchSupported = 'ontouchstart' in window, isTouchSupportedIE10 = navigator.userAgent.match(/Touch/i) != null; jQuery(document).ready(function ($) { if (isTouchSupported || isTouchSupportedIE10) { // this is a mobile device if (window.orientation == 0 || window.orientation == 180) { // run init for portrait orientation } else if (window.orientation == 90 || window.orientation == -90) { // run init for landscape orientation } // detect orientation changes window.addEventListener("orientationchange", function () { if (window.orientation === 0 || window.orientation === 180) { // changed to portrait } else if (window.orientation == 90 || window.orientation == -90) { // changed to landscape } }, false); } else { // this is desktop device // run init for desktops here } }); // ready