What is the best method of re-rendering a web page on orientation change?

后端 未结 8 788
臣服心动
臣服心动 2020-11-28 06:43

I have a fluid CSS layout which is rendering badly on an iphone when I change the orientation. (It looks fine when it is refreshed).

I am using the code below to ref

8条回答
  •  悲哀的现实
    2020-11-28 07:13

    2015 update

    All the other answers are incorrect or outdated. Here's what works:

      window.addEventListener('orientationchange', function () {
        var originalBodyStyle = getComputedStyle(document.body).getPropertyValue('display');
        document.body.style.display='none';
        setTimeout(function () {
          document.body.style.display = originalBodyStyle;
        }, 10);
      });

    The code listens to the orientationchange event and forces a re-flow of the body element by hiding it and showing it 10 milliseconds later. It does not depend on any tags or media queries.

    Other answers suggested using media queries, but you already use them, since you said "It looks fine when it is refreshed".

    Some other answers suggest using location.reload(). This is very inefficient, because it will reload the entire page, including images etc. Especially on mobile, you don't want to do that.

    Yet other answers suggested adding or variations thereof. As of Safari 7, this no longer works. Here's a demo. To make sure you see how it doesn't work, start with the iPad in landscape mode, load the page, then rotate. Notice the page doesn't expand to full height, despite using flexbox all the way.

    Compare that to this page, where we use the hide/show body technique in production.

提交回复
热议问题