最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to resize iframe on window resize - Stack Overflow

programmeradmin1浏览0评论

I am trying to resize the iframe element on window resize like this:

Link to jsfiddle

the only difference is that in my original code I have pdf document as src but not the apple website.

src='link-to-local-pdf'

I want it on window resize to make it respectively resize the iframe itself and not to add scroll on the window but only on the iframe. Can you help?

I am trying to resize the iframe element on window resize like this:

Link to jsfiddle

the only difference is that in my original code I have pdf document as src but not the apple website.

src='link-to-local-pdf'

I want it on window resize to make it respectively resize the iframe itself and not to add scroll on the window but only on the iframe. Can you help?

Share Improve this question edited Dec 13, 2013 at 15:11 peterh 1 asked Dec 13, 2013 at 14:34 mathinvalidnikmathinvalidnik 1,60010 gold badges37 silver badges57 bronze badges 1
  • So you want the iframe to take up as much space as possible without adding scrollbars? – JensB Commented Dec 13, 2013 at 14:51
Add a ment  | 

3 Answers 3

Reset to default 2

Hoping I understood what you are after correctly. Here is an example of a page where the iframe makes itself always just fit inside its parent window.

Working example: http://jsfiddle/My6mj/

javascript:

// set initial size
$( document ).ready(SetIframeSize);

// resize on window resize
$(window).on('resize', SetIframeSize);

function SetIframeSize(){
    $("#external").width($(window).width() - 18); // added margin for scrollbars
    $("#external").height($(window).height() - 35);
}

html:

<div>
    <br/>
    <div id="iframe-wrapper" align="center" style="z-index: 0">
        <iframe id="external" src="http://www.apple./">dada</iframe>
    </div>   
</div>

css:

body {
    overflow:hidden;
}

This should work without JavaScript:

  1. Calculate the aspect ratio of the iframe content (height/width).
  2. Wrap the iframe in a div.
  3. Apply styles to the wrapper:

    .wrap { position: relative; padding-top: /* aspect ratio in % */ overflow: hidden; }

  4. Remove width and height from the iframe.

  5. Apply styles to the iframe:

    iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100% }

This is doing, what you want.

<body>
   <iframe id="the_iframe"></iframe>
</body>

#the_iframe {
    position: absolute;
    left: 50px;
    right: 50px;
    top: 50px;
    bottom: 50px;
}

The trick is the absolute positioning, which is practically relative to its parent. This css gives the the_iframe practically an 50px margin, but in the whole body window.

发布评论

评论列表(0)

  1. 暂无评论