Mobile Safari $(window).height() URL bar discrepancy

前端 未结 4 925
你的背包
你的背包 2020-12-05 15:47

I\'m trying to set a fixed div that\'s 100% the window height. But mobile safari doesn\'t detect the correct window height. It always thinks that the URL bar is part of the

4条回答
  •  醉话见心
    2020-12-05 16:29

    Here's how I figured it out. Its a two step process.

    Step 1 - Check to see if the device is an iPhone or an iPod.

    Step 2 - If it is then check to see if the browser is safari

    // On document ready set the div height to window
    $(document).ready(function(){ 
    
        // Assign a variable for the application being used
        var nVer = navigator.appVersion;
        // Assign a variable for the device being used
        var nAgt = navigator.userAgent;
        var nameOffset,verOffset,ix;
    
    
        // First check to see if the platform is an iPhone or iPod
        if(navigator.platform == 'iPhone' || navigator.platform == 'iPod'){
            // In Safari, the true version is after "Safari" 
            if ((verOffset=nAgt.indexOf('Safari'))!=-1) {
              // Set a variable to use later
              var mobileSafari = 'Safari';
            }
        }
    
        // If is mobile Safari set window height +60
        if (mobileSafari == 'Safari') { 
            // Height + 60px
            $('#right-sidebar').css('height',(($(window).height()) + 60)+'px');
        } else {
            // Else use the default window height
            $('#right-sidebar, .profile').css({'height':(($(window).height()))+'px'});  
        };
    
    
    });
    
    // On window resize run through the sizing again
    $(window).resize(function(){
        // If is mobile Safari set window height +60
        if (mobileSafari == 'Safari') { 
            // Height + 60px
            $('#right-sidebar').css('height',(($(window).height()) + 60)+'px');
        } else {
            // Else use the default window height
            $('#right-sidebar, .profile').css({'height':(($(window).height()))+'px'});  
        };
    });
    

    Then use the mobileSafari variable whenever needed to execute mobile safari specific code.

    Starting with the device first rules out iPads and desktops etc which can also run Safari. Then the second step rules out Chrome and other browsers which can potentially run on these devices.

    Here's a more in depth breakdown of why I did it this way - http://www.ethanhackett.com/?blog=window-height-100-on-mobile-safari-coding-solution

提交回复
热议问题