javascript max viewport height after orientation change Android & iOS

前端 未结 3 1725
遇见更好的自我
遇见更好的自我 2021-01-30 18:43

The Goal:

To find the max viewport height of a device including the space of the address bar so that we can dynamically resize the min-body and push our c

相关标签:
3条回答
  • 2021-01-30 19:19

    This is a simple solution that will append the browsers width and height to the document body on load and window resize.

    jQuery.event.add(window, "load", resize);
    jQuery.event.add(window, "resize", resize);
    
      function resize() 
        {
          var h = jQuery(window).height();
          var w = jQuery(window).width();
          jQuery("body").css({"width": w, "height": h});
        }
    
    0 讨论(0)
  • 2021-01-30 19:20

    Expected values returned in iOS simulator. I can't test for Android at the moment.

    var supportsOrientationChange = "onorientationchange" in window;
    var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
    
    window.onload = updateOrientation();
    
    window.addEventListener(orientationEvent, function() {
        updateOrientation();
    }, false);
    
    function updateOrientation(){
        switch(window.orientation){
        case 0:
        alert(window.outerHeight); // Returns '356' with browser chrome
        break;
    
        case -90:
        alert('Landscape right');
        break;
    
        case 90:
        alert(window.outerHeight); // Returns '208' w browser chrome
        break;
    
        case 180:
        //alert('Portrait view - upside down');
        break;
        }
        var orientation = (window.orientation);
    }
    

    (Note: This code will not test in a browser.)

    0 讨论(0)
  • 2021-01-30 19:20

    You could try a self-invoking closure that monitors the change in orientation by itself. Something like this:

    (function () {
    
        var CurrentHeight;
    
        (function CheckForOrientationChange() {
    
            //var NewHeight = window.screen.availHeight / window.devicePixelRatio;
            //var NewHeight = $(window).height();    
    
            var NewHeight = $('#WidthCheck').width();
    
            if (CurrentHeight && CurrentHeight!== NewHeight ) {
    
                alert(NewHeight); // change here
            }
    
            CurrentHeight = NewHeight;
    
            setTimeout(CheckForOrientationChange, 1000);
    
        })();
    
    })();
    

    Just drop this into the document ready function. For now it checks every second but you can shorten that interval. The jsfiddle is here and you can test it by changing the size of the browser to simulate a mobile browser's change and then you can adapt the code to handle your action.

    0 讨论(0)
提交回复
热议问题