programing

jquery 로드 시 iframe 컨텐츠 높이 가져오기

codeshow 2023. 10. 24. 21:37
반응형

jquery 로드 시 iframe 컨텐츠 높이 가져오기

메인 iframe에 로드하는 도움말 페이지, help.php가 있습니다.php iframe에 로드된 후 이 페이지의 높이를 얻으려면 어떻게 해야 합니까?

토이프레임의 높이를 100%로 스타일링 할 수 없고 오토로 스타일링 할 수 없기 때문에 문의드립니다.그래서 자바스크립트를 사용해야 할 것 같습니다.저는 jQuery를 사용하고 있습니다.

CSS:

body {
    margin: 0;
    padding: 0;
}
.container {
    width: 900px;
    height: 100%;
    margin: 0 auto;
    background: silver;
}
.help-div {
    display: none;
    width: 850px;
    height: 100%;
    position: absolute;
    top: 100px;
    background: orange;
}
#help-frame {
    width: 100%;
    height: auto;
    margin:0;
    padding:0;
}

JS:

$(document).ready(function () {
    $("a.open-help").click(function () {
        $(".help-div").show();
        return false;
    })
})

HTML:

<div class='container'>
    <!-- -->
    <div class='help-div'>
        <p>This is a div with an iframe loading the help page</p>
        <iframe id="help-frame" src="../help.php" width="100%" height="100%" frameborder="1"></iframe>
    </div>  <a class="open-help" href="#">open Help in iFrame</a>

    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>

그래 드디어 좋은 해결책을 찾았습니다.

$('iframe').load(function() {
    this.style.height =
    this.contentWindow.document.body.offsetHeight + 'px';
});

일부 브라우저(구 사파리 및 오페라)는 CSS 렌더링 전에 완료된 로드를 보고하기 때문에 마이크로 타임아웃을 설정하고 iframe의 src를 비워 재할당해야 합니다.

$('iframe').load(function() {
    setTimeout(iResize, 50);
    // Safari and Opera need a kick-start.
    var iSource = document.getElementById('your-iframe-id').src;
    document.getElementById('your-iframe-id').src = '';
    document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
    document.getElementById('your-iframe-id').style.height = 
    document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}

덜 복잡한 답은 사용하는 것입니다..contents()이 프레임에 접근하기 위해서 입니다.그런데 재미있는 것은, 원래의 답변에서 코드를 사용해서 얻은 값과는 다른 값을 돌려준다는 것입니다. 몸에 패딩이 있기 때문이라고 생각합니다.

$('iframe').contents().height() + 'is the height'

도메인 간 통신을 위해 이렇게 해왔기 때문에 불필요하게 복잡할 수도 있습니다.먼저 iFrame의 문서에 jQuery를 넣겠습니다. 이렇게 하면 메모리가 더 많이 소모되지만 스크립트를 한 번만 로드하면 되므로 로드 시간이 늘어나지 않습니다.

iFrame의 jQuery를 사용하여 iFrame 본체의 높이를 가능한 한 빨리 측정한 다음(DOMReady에서) URL 해시를 해당 높이로 설정합니다.그리고 부모 문서에 다음을 추가합니다.onloadiframe의 위치를 살펴보고 필요한 값을 추출하는 iFrame 태그에 대한 event.onDOM Ready는 항상 문서의 로드 이벤트 전에 발생하기 때문에 경합 조건이 발생하지 않아도 값이 정확하게 전달될 것이라고 확신할 수 있습니다.

즉,

...Help.php:

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...및 부모 문서에서:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

Chrome, Firefox 및 IE11에서 작동할 수 있는 다음을 발견했습니다.

$('iframe').load(function () {
    $('iframe').height($('iframe').contents().height());
});

I 프레임 컨텐츠 로드가 완료되면 이벤트가 실행되고 I 프레임 높이가 해당 컨텐츠의 높이로 설정됩니다.이는 IFrame과 동일한 도메인 내의 페이지에 대해서만 작동합니다.

jQuery 없이 이를 수행하는 코드는 요즘에는 사소한 것입니다.

const frame = document.querySelector('iframe')
function syncHeight() {
  this.style.height = `${this.contentWindow.document.body.offsetHeight}px`
}
frame.addEventListener('load', syncHeight)

이벤트의 연결을 해제하는 방법:

frame.removeEventListener('load', syncHeight)

이 작업을 위해 iframe 안에 jquery는 필요 없지만 코드가 훨씬 간단해서 사용합니다.

이것을 당신의 iframe 안에 있는 문서에 넣습니다.

$(document).ready(function() {
  parent.set_size(this.body.offsetHeight + 5 + "px");  
});

작은 창문에 있는 스크롤 바를 없애기 위해 위에 5개를 추가했습니다. 크기에 있어서는 결코 완벽하지 않습니다.

그리고 이것은 부모 문서 안에 있습니다.

function set_size(ht)
{
$("#iframeId").css('height',ht);
}

기본 최소 높이로 시작하여 콘텐츠 크기로 증가하는 단순한 원-라이너.

<iframe src="http://url.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>

이것은 나에게 효과가 있었던 정답입니다.

$(document).ready(function () {
        function resizeIframe() {
            if ($('iframe').contents().find('html').height() > 100) {
                $('iframe').height(($('iframe').contents().find('html').height()) + 'px')
            } else {
                setTimeout(function (e) {
                    resizeIframe();
                }, 50);
            }
        }
        resizeIframe();
    });

승인된 답변$('iframe').load이제 생산할 것입니다.a.indexOf is not a function류(으)로할 수 . 다음으로 업데이트할 수 있습니다.

$('iframe').on('load', function() {
  // ...
});

다음과 비슷한 다른 것은 거의 없습니다..loadjQuery 1.8 이후 더 이상 사용되지 않음: 새 기초 프로젝트를 열 때 "UncaughtTypeError: a.indexOf는 함수가 아닙니다" 오류가 발생했습니다.

이것은 나의 ES6 친절한 노퀘리 테이크입니다.

document.querySelector('iframe').addEventListener('load', function() {
    const iframeBody = this.contentWindow.document.body;
    const height = Math.max(iframeBody.scrollHeight, iframeBody.offsetHeight);
    this.style.height = `${height}px`;
});

iframe 내의 SPA와 연동할 수 있는 jQuery free 솔루션입니다.

document.getElementById('iframe-id').addEventListener('load', function () {
  let that = this;
  setTimeout(function () {
    that.style.height = that.contentWindow.document.body.offsetHeight + 'px';
  }, 2000) // if you're having SPA framework (angularjs for example) inside the iframe, some delay is needed for the content to populate
});

이것은 전체 높이를 찾기 위해 순수 JS를 사용하는 나의 해결책입니다.iframe만족할 만한참고:

  1. iframe이 로드된 후 이 함수를 호출합니다.

  2. iframe 컨텐츠는 호스트 페이지와 동일한 도메인에 있어야 합니다.

     function getIframeBodyTotalHeight() {
     var frm = document.getElementById("appframe");
     var frm_body = frm.contentWindow.document.body;
    
     var body_height = parseInt(frm_body.offsetHeight);
     var body_margin_top = parseInt(window.getComputedStyle(frm_body).getPropertyValue('margin-top').replace("px",""));
     var body_margin_bottom = parseInt(window.getComputedStyle(frm_body).getPropertyValue('margin-bottom').replace("px",""));
     var body_padding_top = parseInt(window.getComputedStyle(frm_body).getPropertyValue('padding-top').replace("px", ""));
     var body_padding_bottom = parseInt(window.getComputedStyle(frm_body).getPropertyValue('padding-bottom').replace("px", ""));
    
     var result = body_height + body_margin_top + body_margin_bottom + body_padding_top + body_padding_bottom;
     return result;
    }
    

언급URL : https://stackoverflow.com/questions/3846132/jquery-get-height-of-iframe-content-when-loaded

반응형