Fancybox - javascript to detect mobile orientation and launch advisory pop-up if portrait

风格不统一 提交于 2019-12-10 11:28:58

问题


I've got the fancybox pop-up to launch OK, but for now only in response to:

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

See example here: www.casedasole.it/testing/popup.html

If you reload the page at less than 400px width, the popup pops up.

But what I need is to change the "if" to whatever indicates that the mobile is in portrait mode. Then the pop-up will say something like: "This website looks better in landscape". I've found references to orientationchange events, but nothing yet that works for detecting whether a mobile is in portrait and, if so, launching the pop-up. The code now is:

if (window.innerWidth < 400 && window.innerHeight < 600)   
{$.fancybox.open([
    {
        href : 'http://www.casedasole.it/images/jarac.jpg'
    }
], {
        padding : 0
}   
);}

回答1:


jsFiddle Demo

What you should really do is just check the width and height of the window. If the width is > than the height then it is landscape. If the height is more than the width then it is portrait.

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

edit

Should just be

var isPortrait = window.innerWidth < window.innerHeight;
if( isPortrait )
{
 $.fancybox.open([
   {
    href : 'http://www.casedasole.it/images/jarac.jpg'
   }
  ], {
   padding : 0
   }   
 );
}



回答2:


I use to compare width against height and works not only for mobile but desktop browsers too, however if you really want to filter mobile devices, then compare features instead.

This is what I normally do :

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


来源:https://stackoverflow.com/questions/21148076/fancybox-javascript-to-detect-mobile-orientation-and-launch-advisory-pop-up-if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!