How to preserve responsive design in mobile browse

2020-07-30 00:34发布

问题:

I would like to load a responsive design website in an iframe as one of my website's pages. However, when it's loaded in the iframe, the site loses its responsiveness.

Using Mashable.com as an example (which is built in responsive design)- my code looks like this:

<body>
    <style>
    body {width:100%;height:100%;margin:0;overflow:hidden;background-color:#252525;}
    #iframe {position:absolute;left:0px;top:0px;}
    </style>

    <iframe id="iframe" name="iframe1" frameborder="0" width="100%" height="100%" src="http://mashable.com"></iframe>
</body>

If you go to mashable.com on your phone, you'll see the responsive design in action. However, if you visit the page above on your phone, mashable's responsive design isn't functioning.

Does anyone know how to load a web page in a div and keep its responsive design?

Thanks in advance!

回答1:

Add the meta tag "viewport" to the head of your page to tell the mobile browser not scale the page. Safari on the desktop already respects the responsive design of the iframe content by default.

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0 maximum-scale=1.0" />

Open this JSBin link on your mobile to test with the meta tag and the following link without the meta tag. To edit open this JSBin page.

NB. Tested on iPhone 5 (iOS6) and Safari 6.



回答2:

You'll have to use jquery:

$('iframe').each(function(){
    var
    $this       = $(this),
    proportion  = $this.data( 'proportion' ),
     w           = $this.attr('width'),
   actual_w    = $this.width();

    if ( ! proportion )
    {
        proportion = $this.attr('height') / w;
        $this.data( 'proportion', proportion );
    }

    if ( actual_w != w )
    {
         $this.css( 'height', Math.round( actual_w * proportion ) + 'px' );
    }
});

Reference: https://gist.github.com/aarongustafson/1313517