내용에 맞게 iframe의 너비와 높이를 조정합니다


300

나는에 대한 해결책이 필요 자동 조정 을 width하고 height의 iframe거의 그 내용에 맞게합니다. 요점은 iframe로드 된 후에 너비와 높이를 변경할 수 있다는 것 입니다. iframe에 포함 된 몸체의 크기 변경을 처리하기 위해 이벤트 작업이 필요하다고 생각합니다.



수락 된 답변이 작동하지 않습니다. 시도 stackoverflow.com/a/31513163/482382
— 스티븐 쇼

답변:


268
<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

8
@ StoneHeart : 예, 크로스 브라우저입니다. DOM 사양에 정의되어 있지 않은 contentWindow 속성으로 인해 코드가 비표준을 준수합니다. DOM 사양에는 contentDocument라는 속성이 있지만 Internet Explorer 6 (및 7?)은이를 지원하지 않습니다. contentWindow 속성을 대신 사용할 수 있으며 모든 일반적인 브라우저 (Gecko, Opera, Webkit, IE)에서 구현됩니다.
— Rafael

30
if (document.getElementById)의 용도는 무엇입니까?
— Ally

55
또한 교차 도메인이 아니라는 것을 잊지 마십시오. 도메인 에 오류 가 발생하는 이유 : 도메인이 다른 경우 'document'속성에 대한 액세스 권한이 거부되었습니다 . 해결책은 여기
— Pierre de LESPINAY

15
조건부는 쓸모 없을뿐 아니라 드문 상황에서 문제가 발생할 수 있습니다. 왜 메소드가 존재하는지 확인한 다음 체크 외부에서 메소드를 사용하고 있습니까?
— JS

6
나는 당신이 의미 하는 것 같지 않기 DOMContentLoaded때문에, developer.mozilla.org/en-US/…DOMContentReady
— Max Heiber

46

크로스 브라우저 jQuery 플러그인 .

iFrame의 컨텐츠 크기를 유지하고 iFrame과 호스트 페이지간에 통신 하는 데 사용 되는 교차 보우 저, 교차 도메인 라이브러리 . jQuery를 사용하거나 사용하지 않고 작동합니다.mutationObserverpostMessage


3
iframe 저항기 라이브러리는 가장 강력한 솔루션입니다.
— kwill

35

지금까지 제공된 모든 솔루션은 단 한 번의 크기 조정 만 설명합니다. 내용이 수정 된 후 iFrame의 크기를 조정할 수 있다고 언급했습니다. 이렇게하려면 iFrame 내에서 함수를 실행해야합니다 (내용이 변경되면 내용이 변경되었다는 이벤트를 발생시켜야 함).

iFrame 내부의 코드가 iFrame 내부의 DOM으로 제한되어 iFrame을 편집 할 수없는 것처럼 보였고 iFrame 외부에서 실행 된 코드가 iFrame 외부의 DOM과 붙어 있었기 때문에 잠시 동안이 문제가 발생했습니다. → iFrame 내부에서 오는 이벤트를 선택하십시오.

해결책은 jQuery에게 어떤 DOM을 사용할 수 있는지 알려줄 수 있다는 것입니다 (동료의 도움을 통해). 이 경우 상위 창의 DOM입니다.

따라서 이와 같은 코드는 필요한 작업을 수행합니다 (iFrame 내에서 실행될 때).

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#IDofControlFiringResizeEvent").click(function () {
            var frame = $('#IDofiframeInMainWindow', window.parent.document);
            var height = jQuery("#IDofContainerInsideiFrame").height();
            frame.height(height + 15);
        });
    });
</script>

이것에 대한 전체 코드는 무엇입니까? 스크립트가 iframe html로 이동한다고 가정합니까?
— Andrew Hundt

이것은 전체 코드이며 iFrame의 HTML 내에서 실행됩니다. "window.parent.document"부분은 jQuery 선택기가 사용자가있는 문서가 아닌 상위 문서의 DOM을 사용해야 함을 지정합니다 (iFrame 내부에 있음).
— Garnaph

13
iframe의 부모 문서와 문서가 모두 같은 도메인에있는 경우에 아름답게 작동 합니다 . 그들이 (또는 둘 다 로컬 파일 인 경우 크롬으로 ) 브라우저의 "동일한 출처"보안 정책이 적용되어 iframe 내용이 부모 문서를 수정하지 못하게합니다.
— user56reinstatemonica8

1
도메인 간 작업을 수행하려는 사람은 window.postMessage (IE8 +)를 살펴보고 호스트 (부모)와 소스 (iframe 내) 문서 모두에 사용자 정의 스크립트가 필요하다는 것을 알고 있어야합니다. jQuery postmessage 플러그인 이 도움이 될 수 있습니다. 호스트와 소스에 스크립트가 필요하기 때문에 JSON-P를 사용하여 호스트가 AJAX로 컨텐츠를로드하는 것이 더 쉬울 수 있습니다.
— user56reinstatemonica8

3
대신 자동으로 이벤트를 시작하는 방법은 jQuery("#IDofControlFiringResizeEvent").click(function ()무엇입니까?
— Ben

33

임베드 용 단일 라이너 솔루션 : 최소 크기로 시작하여 컨텐츠 크기가 증가합니다. 스크립트 태그가 필요 없습니다.

<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>


실행 코드 스 니펫이 Safari 9.1.1에서 작동하지 않습니다. SO 문제가 있습니까?
— Elensar

도메인 간이 아닙니다. 서버가 프레임 페이지에 헤더를 추가해야합니까?
— Finesse

여기에 언급 된 모든 답변 scrollHeight/scrollWidth은 본문 여백을 고려하여 약간 조정해야합니다. 브라우저는 문서의 본문 요소에 0이 아닌 기본 여백을 적용합니다 (프레임에로드 된 내용에도 적용 가능). 내가 찾은 작업 솔루션은 이것을 추가하는 것 parseInt(window.getComputedStyle(this.contentDocument.body).margin입니다.
— Stan

24

iframe 컨텐츠가 동일한 도메인에서 온 경우에는 효과적입니다. 그래도 jQuery가 필요합니다.

$('#iframe_id').load(function () {
    $(this).height($(this).contents().height());
    $(this).width($(this).contents().width());
});

동적으로 크기를 조정하려면 다음을 수행하십시오.

<script language="javaScript">
<!--
function autoResize(){
    $('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>

그런 다음 iframe 이로 드되는 페이지에서 다음을 추가하십시오.

<script language="javaScript">
function resize()
{
    window.parent.autoResize();
}

$(window).on('resize', resize);
</script>

출처가 다른 도메인에서 왔을 때이를 수행하는 간단한 방법이 있습니까?
— BruceJohnJennerLawso

15

jQuery를 사용하지 않으려는 경우 브라우저 간 솔루션은 다음과 같습니다.

/**
 * Resizes the given iFrame width so it fits its content
 * @param e The iframe to resize
 */
function resizeIframeWidth(e){
    // Set width of iframe according to its content
    if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
        e.width = e.contentWindow.document.body.scrollWidth;
    else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
        e.width = e.contentDocument.body.scrollWidth + 35;
    else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
        e.width = e.contentDocument.body.offsetWidth + 35;
}

1
이상하다. 나를 위해 iframe의 매우 이상한 너비를 계산합니다. 내용 폭은 750이고 그것을 300으로 계산합니다. 왜 아이디어가 있습니까?
— Rob

이 코드로 연주했습니다 (높이 옵션 추가). iFrame 높이를 100 %로 설정하면 약 200px로 제한됩니다. iFrame 높이를 600px로 설정하면 그대로 유지됩니다. @RobertJagoda 당신은 이것에 대한 해결책을 얻었습니까?
— iaindownie

9

지구상의 모든 것을 시도한 후에 이것은 실제로 저에게 효과적입니다.

index.html

<style type="text/css">
html, body{
  width:100%;
  height:100%;
  overflow:hidden;
  margin:0px;   
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>

그것은 말한다 : catch되지 않은 형식 오류가 : HTMLIFrameElement.onload에서 ((색인) : 204) : $가 자동 크기 (200 (인덱스))에서 함수가 아닙니다
— 마이클 로저스

2
@Michael Rogers $와 충돌이 있거나 jQuery.js 파일을 포함시키는 것을 잊어 버렸습니다. 일반적인 함수 stackoverflow.com/questions/6109847/… 또는 $를 jQuery로 대체
— Adrian P.

8

이 코드를 사용하여 모든 iframe (클래스 autoHeight 포함)이 페이지에로드 될 때 높이를 자동 조정합니다. 테스트되었으며 IE, FF, Chrome, Safari 및 Opera에서 작동합니다.

function doIframe() {
    var $iframes = $("iframe.autoHeight"); 
    $iframes.each(function() {
        var iframe = this;
        $(iframe).load(function() {
            setHeight(iframe);
        });
    });
}

function setHeight(e) {
  e.height = e.contentWindow.document.body.scrollHeight + 35;
}

$(window).load(function() {
    doIframe();
});

2
이 마법 35는 무엇입니까? 어떤 브라우저와 OS를 측정 했습니까?
— h2stein

이제 왜 35 픽셀을 추가했는지 모르겠습니다. 그러나 FF, IE (7, 8, 9) 및 Chrome에서 테스트했으며 제대로 작동했다고 말할 수 있습니다.
— petriq

3
35는 스크롤바 두께 일뿐입니다.
— Sadegh

나는 이것을 작동시키기 위해 이것을 약간 조정해야했다-setHeight (iframe); 직접 (주변의 $ (iframe) .load () 래퍼를 제거했습니다.
— shacker

추가 된 매직 35 픽셀은 iframe 패딩을 고려합니다. iframe에 iframe의 내용을 채워 넣지 않아야한다고 덧붙여 야합니다.
— Filipe Melo

5

이것은 견고한 증거 솔루션입니다

function resizer(id)
{

var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;

var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

document.getElementById(id).style.height=height;
document.getElementById(id).style.width=width;

}

HTML

<IFRAME SRC="blah.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>

3

위의 Garnaph의 훌륭한 솔루션을 약간 수정했습니다. 그의 솔루션이 이벤트 직전의 크기를 기준으로 iframe 크기를 수정 한 것처럼 보입니다. 내 상황 (iframe을 통한 이메일 제출)의 경우 제출 직후 변경하려면 iframe 높이가 필요했습니다. 예를 들어 제출 후 유효성 검사 오류 또는 "감사합니다"메시지를 표시합니다.

방금 중첩 click () 함수를 제거하고 iframe html에 넣었습니다.

<script type="text/javascript">
    jQuery(document).ready(function () {
        var frame = $('#IDofiframeInMainWindow', window.parent.document);
        var height = jQuery("#IDofContainerInsideiFrame").height();
        frame.height(height + 15);
    });
</script>

나를 위해 일했지만 크로스 브라우저 기능에 대해서는 확실하지 않습니다.


3

IFRAME 컨텐츠와 부모 윈도우를 모두 제어 할 수 있다면 iFrame Resizer 가 필요합니다 .

이 라이브러리를 사용하면 포함 된 컨텐츠에 맞게 동일한 도메인 간 및 iframe의 높이와 너비를 자동으로 조정할 수 있습니다. iFrame 사용과 관련된 가장 일반적인 문제를 해결하기 위해 다음과 같은 다양한 기능을 제공합니다.

  • 컨텐츠 크기에 맞게 iFrame의 높이 및 너비 크기 조정.
  • 여러 개의 중첩 된 iFrame과 작동합니다.
  • 교차 도메인 iFrame에 대한 도메인 인증.
  • 복잡한 CSS 레이아웃을 지원하기 위해 다양한 페이지 크기 계산 방법을 제공합니다.
  • MutationObserver를 사용하여 페이지 크기를 조정할 수있는 DOM 변경을 감지합니다.
  • 페이지 크기를 조정할 수있는 이벤트 (창 크기 조정, CSS 애니메이션 및 전환, 방향 변경 및 마우스 이벤트)를 감지합니다.
  • postMessage를 통해 iFrame과 호스트 페이지 간 메시징이 간소화되었습니다.
  • iFrame에서 페이지 링크를 수정하고 iFrame과 부모 페이지 사이의 링크를 지원합니다.
  • 사용자 정의 크기 조정 및 스크롤 방법을 제공합니다.
  • 부모 위치와 뷰포트 크기를 iFrame에 노출합니다.
  • ViewerJS와 함께 작동하여 PDF 및 ODF 문서를 지원합니다.
  • IE8까지 폴백 지원.

2

위의 방법으로는 모두 작동하지 않습니다.

자바 스크립트 :

function resizer(id) {
        var doc = document.getElementById(id).contentWindow.document;
        var body_ = doc.body, html_ = doc.documentElement;

        var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
        var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);

        document.getElementById(id).style.height = height;
        document.getElementById(id).style.width = width;

    }

html :

<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv"  >
         <input id="txtHeight"/>height     <input id="txtWidth"/>width     
        <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0"  ></iframe>
        <iframe src="left.aspx" name="leftFrame" scrolling="yes"   id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
        <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; "  onload="resizer('Iframe2');" ></iframe>
</div>

환경 : IE 10, Windows 7 x64


2

실험 후 다른 해결책을 찾았습니다. 나는 원래이 질문에 '최고의 답변'으로 표시된 코드를 시도했지만 작동하지 않았습니다. 내 생각에 당시 내 프로그램의 iframe이 동적으로 생성 되었기 때문입니다. 내가 사용한 코드는 다음과 같습니다.

로드중인 iframe 내부의 자바 스크립트 :

window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };

스크롤 막대를 제거하려면 높이에 4 개 이상의 픽셀을 추가해야합니다 (일부 이상한 버그 / iframe의 영향). 너비는 심지어 낯선 것입니다. 몸 너비에 18px를 추가하는 것이 안전합니다. 또한 iframe 바디에 CSS가 적용되어 있는지 확인하십시오 (아래).

html, body {
   margin:0;
   padding:0;
   display:table;
}

iframe {
   border:0;
   padding:0;
   margin:0;
}

iframe의 HTML은 다음과 같습니다.

<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>

내 iframe 내의 모든 코드는 다음과 같습니다.

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload</title>
    <style type="text/css">
    html, body {
        margin:0;
        padding:0;
        display:table;
    }
    </style>
    <script type="text/javascript">
    window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
    </script>
</head>
<body>
    This is a test.<br>
    testing
</body>
</html>

크롬과 파이어 폭스 (windows xp)에서 약간의 테스트를 수행했습니다. 아직 더 많은 테스트를 진행 중이므로 어떻게 작동하는지 알려주세요.


감사합니다. 이것은 내가 테스트 한 모바일 브라우저에서 훌륭하게 작동하며 iframe 크기 조정에 문제가있는 곳입니다!
— Mircea Sandu

:-) iframe이 Ajax보다 훨씬 효율적이고 더 나은 브라우저 지원을 제공한다는 것을 알았습니다.
— www139

1
감사합니다!!! 주로 사람들이 알고 있다고 가정하지 않고 코드를 넣을 위치를 지정한 유일한 사람이기 때문입니다. 이 간단한 솔루션은 Wordpress 사이트의 동일한 도메인에서 동적 콘텐츠를 프레이밍하기 위해 완벽하게 작동했습니다 (Firefox, Chrome, Edge). 다양한 길이의 동적 내용을 출력하는 양식 선택이 있습니다. iFrame이 아름답게 조정됩니다. .clientHeight + 5 + 'px'를 조정해야했습니다. 및 clientWidth + 18 + 'px'; 더 많은 픽셀이 될 수 있습니다. 그리고 나는 왜 디스플레이가 잘 모르겠습니다 : table; CSS에서 필요했기 때문에 내 목적으로 주석 처리했습니다. 다시 감사합니다.
— Heres2u

1

이것이 내가하는 방법입니다 (FF / Chrome에서 테스트 됨).

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>

Microsoft가 그것에 대해 신경 쓰지 않는다면 누가 신경 써야합니까?
— m3nda 2012 년

1

몇 가지 방법이 있습니다.

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>

그리고 다른 대안

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>

위에 표시된대로 두 가지 대안으로 스크롤을 숨기려면

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>

두 번째 코드로 해킹

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>

iFrame의 스크롤 막대를 숨기려면 부모가 "오버플로 : 숨겨 짐"으로 만들어 스크롤 막대를 숨기고 iFrame은 최대 150 % 너비와 높이로 이동하여 스크롤 막대를 페이지 외부로 강제합니다. 스크롤 막대가 없으면 iframe이 페이지 경계를 초과하지 않을 수 있습니다. iFrame의 스크롤 막대를 전체 너비로 숨 깁니다!

소스 : iframe 자동 높이 설정


당신이 제공 한 예제는 iframe의 전체 크기를 자동으로 조정하지 않고 모든 내부 컨텐츠에 맞게 iframe의 높이를 자동 조정하지 않아야합니다. 질문에 대답하지 않습니다.
— nickornotto


1

이 resizer가 더 잘 작동한다는 것을 알았습니다.

function resizer(id)
{

    var doc = document.getElementById(id).contentWindow.document;
    var body_ = doc.body;
    var html_ = doc.documentElement;

    var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight,     html_.scrollHeight, html_.offsetHeight );
    var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

    document.getElementById(id).height = height;
    document.getElementById(id).width = width;

}

스타일 객체가 제거되었습니다.


Chrome / Win10에서 작동하지 않습니다. 콘텐츠가 일부가 잘려 있습니다.
— glenneroo

1

jQuery에서 이것은 나에게 가장 좋은 옵션입니다. 도와 드릴게요!

iframe

<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>

jQuery

<script>            
        var valueSize = $( "#iframe" ).offset();
        var totalsize = (valueSize.top * 2) + valueSize.left;

        $( "#iframe" ).height(totalsize);            

</script>

1

문맥

웹 확장의 맥락에서 직접해야했습니다. 이 웹 확장 프로그램은 각 페이지에 일부 UI를 삽입하며이 UI는 안에 있습니다 iframe. 내부의 내용 iframe은 동적이므로 너비와 높이를 다시 조정해야했습니다.iframe 자체 .

나는 React를 사용한다 하지만 개념은 모든 라이브러리에 적용됩니다.

내 솔루션 (이것은 페이지와 iframe을 모두 제어한다고 가정합니다)

내부에서 iframe나는 body스타일이 정말로 큰 치수를 갖도록 변경했습니다 . 그러면 필요한 모든 공간을 사용하여 내부 요소를 배치 할 수 있습니다. 제작 width및 height100 %가 저에게 효과가 없었습니다 (iframe에 기본값이 width = 300px있고 height = 150px)

/* something like this */
body {
  width: 99999px;
  height: 99999px;
}

그런 다음 모든 iframe UI를 div 안에 삽입하고 스타일을주었습니다.

#ui-root {
  display: 'inline-block';     
}

이 안에 내 응용 프로그램을 렌더링 한 후 #ui-root( React 에서이 작업을 수행합니다. componentDidMount)이 div의 크기를 계산하고 다음을 사용하여 부모 페이지와 동기화합니다 window.postMessage.

let elRect = el.getBoundingClientRect()
window.parent.postMessage({
  type: 'resize-iframe',
  payload: {
    width: elRect.width,
    height: elRect.height
  }
}, '*')

부모 프레임에서 나는 다음과 같이합니다 :

window.addEventListener('message', (ev) => {
  if(ev.data.type && ev.data.type === 'resize-iframe') {
    iframe.style.width = ev.data.payload.width + 'px'
    iframe.style.height = ev.data.payload.height + 'px'
  }
}, false)

좋은 해결책! 감사!
— redelschaap


0

게시물이 오래되었다는 것을 알고 있지만 이것이 또 다른 방법이라고 생각합니다. 방금 코드를 구현했습니다. 페이지로드 및 페이지 크기 조정 모두에서 완벽하게 작동합니다.

var videoHeight;
var videoWidth;
var iframeHeight;
var iframeWidth;

function resizeIframe(){
    videoHeight = $('.video-container').height();//iframe parent div's height
    videoWidth = $('.video-container').width();//iframe parent div's width

    iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
    iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
}
resizeIframe();


$(window).on('resize', function(){
    resizeIframe();
});

0

헤더에 배치 할 자바 스크립트 :

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

다음은 iframe HTML 코드입니다.

<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>

CSS 스타일 시트

>

.spec_iframe {
        width: 100%;
        overflow: hidden;
    }

0

angularjs 지시문 속성의 경우 :

G.directive ( 'previewIframe', function () {
return {
    restrict : 'A',
    replace : true,
    scope : true,
    link : function ( scope, elem, attrs ) {
        elem.on ( 'load', function ( e ) {
            var currentH = this.contentWindow.document.body.scrollHeight;
            this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
        } );
    }
};
} );

iframe, 텍스트, 광고 등에 대해 일반적으로 수행되는 스케일링을 카운터 링 할 수 있도록 백분율을 주목하십시오. 스케일링이 구현되지 않은 경우 단순히 0을 넣으십시오.


0

이것이 내가로드 할 때 또는 일이 바뀔 때의 방법입니다.

parent.jQuery("#frame").height(document.body.scrollHeight+50);

0

분명히 많은 시나리오가 있지만 문서와 iframe에 대해 동일한 도메인을 가지고 있으며 iframe 컨텐츠의 끝 부분에이를 고정시킬 수있었습니다.

var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';

그러면 부모 컨테이너가 '찾기'되고 퍼지 팩터에 50 픽셀을 더한 길이가 설정되어 스크롤 막대가 제거됩니다.

문서 높이 변경을 '관찰'할 것은 없습니다. 이것은 사용 사례에 필요하지 않았습니다. 내 대답에는 부모 / iframe 콘텐츠에 구운 ID를 사용하지 않고 부모 컨테이너를 참조하는 수단을 제공합니다.


0

고정 종횡비로 살 수 있고 반응 형 iframe 을 원한다면이 코드가 유용합니다. CSS 규칙 일뿐입니다.

.iframe-container {
  overflow: hidden;
  /* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16= 
  0.5625) */
  padding-top: 56.25%;
  position: relative;
}
.iframe-container iframe {
  border: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

iframe에는 컨테이너로 div가 있어야합니다.

<div class="iframe-container">
   <iframe src="http://example.org"></iframe>
</div>

소스 코드는이 사이트를 기반으로 하며 Ben Marshall 에 대한 설명이 좋습니다.


-1

단순성 :

var iframe = $("#myframe");
$(iframe.get(0).contentWindow).on("resize", function(){
    iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth);
    iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight);
});

-1

내용이 매우 간단한 HTML 인 경우 가장 간단한 방법은 자바 스크립트로 iframe을 제거하는 것입니다

HTML 코드 :

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>

자바 스크립트 코드 :

function removeIframe(obj) {
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    obj.remove();
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}

1
부모 문서 개요가 변경됩니다. 그림이있는 그림으로 다른 문서를 원한다면 문서 개요를 간결하게 유지하지 않습니다. 다른 유스 케이스이지만 개요 이유로 인해 코드 스 니펫을 iframe으로 옮기고 싶었습니다.
— Henry 's Cat

-2
<iframe src="hello.html" sandbox="allow-same-origin"
        onload="this.style.height=(this.contentWindow.document.body.scrollHeight+20)+'px';this.style.width=(this.contentWindow.document.body.scrollWidth+20)+'px';">
</iframe>

이것은 CSS가 아니며 JS입니다.
— clifgriffin
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.