简体   繁体   中英

How to automatically resize iframe content size when browser window resize?

I am now making a website which will display a spot on a map(not google map). I used an iframe to contain the map and I would like the map to resize the width according to browser window width.

This is my code:

<iframe width='1800' height='300' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='http://f.amap.com/xxxxxxxxxx'></iframe>

To resize the iframe, I simply changed the width and height of the iframe using jquery code like this:

$(window).resize(function(){
var window_width = $(window).width();
$('iframe').width(window_width);
});

However, it changes the width of the iframe only and the contents cannot be resized. How can I resize the content when the window resizes? Thank you very much!

Your site is restricted from making changes to the content of an iframe. If you control the site inside the iframe, you can set up a message-system between the two sites. It might be worth checking if one exists even if you don't control the other site.

Otherwise, I would recommend simply refreshing the content of the iframe:

$( '#iframe' ).attr( 'src', function ( i, val ) { return val; });

As misorude mentioned in a comment you should contain this line so it doesn't fire immediately upon resize, since that would send an unreasonable amount of requests to the remote site.

You just need to set the max-width property to 100% .

<iframe width='1800' height='300' style="max-width:100%" frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='http://f.amap.com/xxxxxxxxxx'> 
</iframe>

this will resize according to the browser window.

You can set width: 100% with CSS. check this : http://jsfiddle.net/w8xeotv4/

Assuming you're not running into CORS issues and the target site is responsive, you can try something like this

$(window).resize(function(){
  var window_width = $(window).width();
  $('iframe').width(window_width);
  $('iframe').contents().width(window_width);
});

Edit

Sorry, this was a very bad answer, not sure what I was thinking when I wrote this. The accepted answer is the best way to go about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM