How to get the height of an iframe with javascript from inside the iframe? What about pages with multiple iframes?

后端 未结 5 373
粉色の甜心
粉色の甜心 2020-12-31 01:38

Is there a way to detect the height and width of an iframe, by executing a script from inside the iframe? I need to dynamically position some elements in the iframe accordi

相关标签:
5条回答
  • 2020-12-31 01:57

    may be a bit late, as all the other answers are older :-) but... here´s my solution. Tested in actual FF, Chrome and Safari 5.0.

    css:

    iframe {border:0; overflow:hidden;}
    

    javascript:

    $(document).ready(function(){
        $("iframe").load( function () {
            var c = (this.contentWindow || this.contentDocument);
            if (c.document) d = c.document;
            $(this).css({
                height: $(d).outerHeight(),
                width: $(d).outerWidth()
            });
        });
    });
    

    Hope this will help anybody.

    0 讨论(0)
  • 2020-12-31 02:04

    Be aware that code like this:

    var thisIframesHeight = window.parent.$("iframe.itsID").height();
    

    will only be safe if the source of the iframe and parent window are from the same domain. If not you will get permission denied problems and you will have to take another approach.

    0 讨论(0)
  • 2020-12-31 02:13

    If your iframe’s page and its parent page are served from different domains (meaning you can’t access the parent page’s DOM properties from the iframe page), then I think it’s the same as when you’re trying to work out the viewport height.

    For that, see:

    • Get the browser viewport dimensions with JavaScript

    Or possibly this:

    • http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
    0 讨论(0)
  • 2020-12-31 02:22

    Each <iframe> would need an id I suppose. And then inside the <iframe> you would reference it like this:

    var thisIframesHeight = window.parent.$("iframe#itsID").height();
    
    0 讨论(0)
  • 2020-12-31 02:22

    yes, you can execute parent's window function from inside the frame, and pass parameters, like this:

    window.parent.FUNC_NAME(iframe_height,iframe_width)
    

    just remember to define function FUNC_NAME in the parent window

    0 讨论(0)
提交回复
热议问题