开发者

How to prevent gaining additional width after orientation change in mobile-safari

In Mobile Safari on my iPad I get some weird behaviour after changing the device orientation. Here is my test file:

<!DOCTYPE HTML>
<html>
    <head>
        <meta name="viewport" content="initial-scale=0.7" />
        <style>
            #block {
                border: 1px solid red;
                background-color: yellow;
   开发者_如何学编程             font-size: 400%;
                width: 700px;
                height: 500px;
            }   
        </style>
    </head>
    <body>
        <div id="block">Hello world!</div>
    </body>
</html>

You can view it in Mobile Safari at this URL:

http://fiddle.jshell.net/eterps/jsTqj/show/

When I go the URL with my iPad in portrait orientation and make some swipe gestures the page does not scroll, which is correct.

However when I rotate the device to landscape mode and make some swipe gestures I gained extra space on the right for no apparent reason.

But even weirder is the fact that when I restart mobile safari and go to the URL while being in landscape orientation all the time, the extra space on the right is not present.

Why does the extra space to the right appear after a change in orientation? And how can I prevent it?


When you rotate the de vice, mobile safari resizes the viewport to match the new orientation.


It seems like mobile safari tries to hold view position in the center of the screen. You can check this by following parameters window.outerWidth and window.scrollX. They are different after load page and changing the orientation portrait -> landscape -> portrait.

I think this topic is related to other discussion Mobile site resize on orientation change not working in Safari

You can force the redraw of page and hiding white space by following script

$(window).bind('orientationchange', function() { 
  var oldWidth = $('body').innerWidth();
  $('body').width(oldWidth + 1); // Force redraw
  $('body').width(''); // Return to previous state in case if width set by css, otherwise use  $('body').width(oldWidth);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜