Czy iframe automatycznie dostosowuje wysokość zgodnie z zawartością bez użycia paska przewijania? [duplikat]

To pytanie ma już odpowiedź tutaj:

Na przykład:

<iframe name="Stack" src="http://stackoverflow.com/" width="740"
        frameborder="0" scrolling="no" id="iframe"> ...
</iframe>

Chcę, aby był w stanie dostosować swoją wysokość do zawartości wewnątrz, bez użycia przewijania.

Author: David Cain, 2012-04-02

17 answers

Dodaj to do sekcji <head>:

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

I zmień iframe na to:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

Jak znaleźć na SitePoint dyskusja .

 532
Author: hjpotter92,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-10 09:11:28

Możesz użyć tej biblioteki, która początkowo prawidłowo dopasowuje ramkę iframe, a także utrzymuje ją we właściwym rozmiarze, wykrywając, kiedy zmienia się rozmiar zawartości iframe (poprzez regularne sprawdzanie w setInterval lub w MutationObserver) i zmieniając jej rozmiar.

Https://github.com/davidjbradshaw/iframe-resizer

Działa to zarówno z ramkami iFrame cross, jak i z tymi samymi domenami.

 76
Author: user2684310,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-05 20:24:37

Sugestia hjpotter92 nie działa w safari! Zrobiłem małą korektę skryptu, więc teraz działa również w Safari.

Jedyną dokonaną zmianą jest Resetowanie wysokości do 0 przy każdym obciążeniu, aby umożliwić niektórym przeglądarkom zmniejszenie wysokości.

Dodaj to do <head> tag:

<script type="text/javascript">
  function resizeIframe(obj){
     obj.style.height = 0;
     obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

I dodaj następujący atrybut onload do ramki iframe, tak jak

<iframe onload='resizeIframe(this)'></iframe>
 36
Author: Allan P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-29 17:26:52

Oto wersja kompaktowa:

<iframe src="hello.html"
        onload="this.style.height=this.contentDocument.body.scrollHeight +'px';">
</iframe>
 33
Author: Chong Lip Phang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-23 21:45:39

Odpowiedź hjpotter92 działa wystarczająco dobrze w niektórych przypadkach, ale znalazłem zawartość iframe często dostał dół obcięty w Firefox & IE, podczas gdy dobrze w Chrome.

Poniżej działa dobrze dla mnie i rozwiązuje problem przycinania. Kod został znaleziony w http://www.dyn-web.com/tutorials/iframes/height / . dokonałem niewielkiej modyfikacji, aby usunąć atrybut onload z HTML. Umieść następujący kod po <iframe> HTML i przed zamknięciem </body> tag:

<script type="text/javascript">
function getDocHeight(doc) {
    doc = doc || document;
    // stackoverflow.com/questions/1145850/
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}

function setIframeHeight(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}

document.getElementById('ifrm').onload = function() { // Adjust the Id accordingly
    setIframeHeight(this.id);
}
</script>

Twój iframe HTML:

<iframe id="ifrm" src="some-iframe-content.html"></iframe>

UWAGA jeśli wolisz włączyć Javascript w <head> dokumentu, możesz powrócić do korzystania z wbudowanego atrybutu onload w iframe HTML, jak na stronie internetowej dyn-web.

 11
Author: Jimadine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-04 12:02:25

Unikaj wbudowanego JavaScript; możesz użyć klasy:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

I odwołaj się do niego jQuery:

$('.iframe-full-height').on('load', function(){
    this.style.height=this.contentDocument.body.scrollHeight +'px';
});
 10
Author: rybo111,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-29 17:35:44

JQuery ' S .metoda contents () metoda pozwala nam przeszukiwać bezpośrednie dzieci elementu w drzewie DOM.

JQuery:

$('iframe').height( $('iframe').contents().outerHeight() );

Pamiętaj, że treść strony wewnątrz ramki iframe musi mieć swoją wysokość

CSS:

body {
  height: auto;
  overflow: auto
}
 5
Author: Nathalia Xavier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-24 14:22:39

To działa dla mnie (również z wieloma ramkami iframe na jednej stronie):

$('iframe').load(function(){$(this).height($(this).contents().outerHeight());});
 2
Author: user2992220,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-17 06:57:08

To działa dla mnie (głównie).

Umieść to na dole swojej strony.

<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script type="application/javascript" src="/script/jquery.browser.js">
</script>

<script type="application/javascript" src="/script/jquery-iframe-auto-height.js">
</script>

<script type="application/javascript"> 
  jQuery('iframe').iframeAutoHeight();
  $(window).load(
      function() {
          jQuery('iframe').iframeAutoHeight();  
      }
  );

  // for when content is not html e.g. a PDF
  function setIframeHeight() {
      $('.iframe_fullHeight').each(
          function (i, item) {
              item.height = $(document).height();
          }
      );
  };

  $(document).ready( function () {
      setIframeHeight();
  });
  $(window).resize( function () {
      setIframeHeight();
  });
</script> 
Pierwsza połowa pochodzi z??? i działa, gdy w ramce iframe znajduje się html. Druga połowa ustawia ramkę iframe na wysokość strony (nie Wysokość zawartości), gdy Klasa iframes to iframe_fullHeight. Możesz tego użyć, jeśli zawartość jest plikiem PDF lub innym podobnym, ale musisz ustawić klasę. Może być również używany tylko wtedy, gdy odpowiednia jest pełna wysokość.

Uwaga: z jakiegoś powodu, gdy przelicza się po oknie Zmień rozmiar, to się pomyli.

 2
Author: ctrl-alt-delor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-03 17:02:47
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).height=(newheight) + "px";
    document.getElementById(id).width=(newwidth) + "px"; 
}

Dodaj to do iframe: onload= " autoResize ('youriframeid') "

 1
Author: Simon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 16:30:25
jq2('#stocks_iframe').load(function(){
var iframe_width = jq2('#stocks_iframe').contents().outerHeight() ; 
jq2('#stocks_iframe').css('height',iframe_width); });

<iframe id='stocks_iframe' style='width:100%;height:0px;' frameborder='0'>
 1
Author: Айдън Бейтулов,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 08:52:11

Spróbuj tego dla IE11

<iframe name="Stack" src="http://stackoverflow.com/" style='height: 100%; width: 100%;' frameborder="0" scrolling="no" id="iframe">...</iframe>
 1
Author: Lucky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-09 22:09:27

W przeszłości miałem problemy z wywołaniem iframe.Ładowanie dynamicznie tworzonych ramek iFrame, więc wybrałem takie podejście do ustawiania rozmiaru ramki iframe:

IFrame View

var height = $("body").outerHeight();
parent.SetIFrameHeight(height);

Widok Główny

SetIFrameHeight = function(height) {
    $("#iFrameWrapper").height(height);
}

(to zadziała tylko wtedy, gdy oba widoki są w tej samej domenie)

 0
Author: Owen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-25 14:29:08

Zrobiłem to z AngularJS. Angular nie ma ng-load, ale powstał moduł 3rd party; zainstaluj za pomocą bowera poniżej, lub znajdź go tutaj: https://github.com/andrefarzat/ng-load

Pobierz dyrektywę ngLoad: bower install ng-load --save

Konfiguracja iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Kontroler resizeIframe funkcja:

$scope.resizeIframe = function (event) {
    console.log("iframe loaded!");
    var iframe = event.target;
    iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
};
 0
Author: Charles Naccio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-05 23:06:56
<script type="text/javascript">
  function resizeIframe(obj) {
    obj.style.height = 0;
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
  }
</script>

To nie działa w chrome. Ale praca dla Firefoksa.

 -2
Author: santoshs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-18 16:03:25

Chciałem, aby iframe zachowywał się jak normalna strona( musiałem zrobić pełnoekranowy baner wewnątrz elementu iframe), więc oto mój skrypt:

    (function (window, undefined) {

    var frame,
        lastKnownFrameHeight = 0,
        maxFrameLoadedTries = 5,
        maxResizeCheckTries = 20;

    //Resize iframe on window resize
    addEvent(window, 'resize', resizeFrame);

    var iframeCheckInterval = window.setInterval(function () {
        maxFrameLoadedTries--;
        var frames = document.getElementsByTagName('iframe');
        if (maxFrameLoadedTries == 0 || frames.length) {
            clearInterval(iframeCheckInterval);
            frame = frames[0];
            addEvent(frame, 'load', resizeFrame);
            var resizeCheckInterval = setInterval(function () {
                resizeFrame();
                maxResizeCheckTries--;
                if (maxResizeCheckTries == 0) {
                    clearInterval(resizeCheckInterval);
                }
            }, 1000);
            resizeFrame();
        }
    }, 500);

    function resizeFrame() {
        if (frame) {
            var frameHeight = frame.contentWindow.document.body.scrollHeight;
            if (frameHeight !== lastKnownFrameHeight) {
                lastKnownFrameHeight = frameHeight;

                var viewportWidth = document.documentElement.clientWidth;
                if (document.compatMode && document.compatMode === 'BackCompat') {
                    viewportWidth = document.body.clientWidth;
                }

                frame.setAttribute('width', viewportWidth);
                frame.setAttribute('height', lastKnownFrameHeight);

                frame.style.width = viewportWidth + 'px';
                frame.style.height = frameHeight + 'px';
            }
        }
    }

    //--------------------------------------------------------------
    //  Cross-browser helpers
    //--------------------------------------------------------------

    function addEvent(elem, event, fn) {
        if (elem.addEventListener) {
            elem.addEventListener(event, fn, false);
        } else {
            elem.attachEvent("on" + event, function () {
                return (fn.call(elem, window.event));
            });
        }
    }

})(window);

Funkcje są oczywiste i mają komentarze, aby dokładniej wyjaśnić ich cel.

 -2
Author: Христо Панайотов,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 21:56:39

Ta opcja będzie działać w 100%

<iframe id='iframe2' src="url.com" frameborder="0" style="overflow: hidden; height: 100%; width: 100%; position: absolute;" height="100%" width="100%"></iframe>
 -3
Author: Vijay Chouhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-15 10:14:47