Resizing an iframe's width on window resize

2019-06-07 23:41发布

问题:

I want to put an iframe next to a sidebar. The sidebar has a constant with of 250px and I want the iframe's width to fill the rest of the screen. So it's width would be window size minus 250px. And I would need this to change dynamically. I'm stick with my existing code.

<script type="text/javascript">$(window).resize(function() {
  $('iframe').prepend(width:$(window).width()px;);

});

</script>
<div style="float:left;"><iframe src="iframe url" 
frameborder="0" 
noresize="noresize" id ="iframe"
style="position:absolute; background:transparent; width:75%;height:100%;top:38px;border:none;padding:0;" />
</iframe>
</div>

This is the javascript and the iframe. What am I doing wrong?

回答1:

Use this JS:

$(function() {
   var newwidth = $(window).width() - 250;
   $('iframe').css({width: newwidth+'px'});
});

$(window).resize(function() {
   var newwidth = $(window).width() - 250;
   $('iframe').css({width: newwidth+'px'});
});

You should also make the surrounding DIV position:relative to make use of the absolute positioning.



回答2:

This will work to fill any space you have responsively and keep original size if screen is even bigger: https://jsfiddle.net/koaab543/2/

I'm using original height and width to calculate proportions. Then getting current width that is limited to space size with css, and deriving new height from that.

height / width = x / currentWidth

function responseveIframe() {
  $('iframe').height(
    $('iframe').attr("height") / $('iframe').attr("width") * $('iframe').width()
  );
}

responseveIframe();

$(window).resize(function() {
  responseveIframe();
});
iframe {
  max-width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<iframe width="854" height="480" src="https://www.youtube.com/embed/C0DPdy98e4c"></iframe>