Program Club

콘텐츠 높이에 따라 iframe 높이 크기 조정

proclub 2020. 11. 5. 19:47
반응형

콘텐츠 높이에 따라 iframe 높이 크기 조정


웹 사이트에서 블로그 페이지를 열고 있습니다. 문제는 iframe에 너비를 줄 수 있지만 높이는 동적이어야 iframe에 스크롤바가없고 단일 페이지처럼 보입니다.

콘텐츠의 높이를 계산하기 위해 다양한 JavaScript 코드를 시도했지만 모두 액세스 거부 권한 오류를 제공하며 아무 소용이 없습니다.

<iframe src="http://bagtheplanet.blogspot.com/" name="ifrm" id="ifrm" width="1024px" ></iframe>

Ajax를 사용하여 높이를 계산하거나 PHP를 사용할 수 있습니까?


두 개의 하위 질문에 직접 답하려면 : 아니요, Ajax로이 작업을 수행 할 수 없으며 PHP로 계산할 수도 없습니다.

내가 과거에 한 것은 페이지의 본문 높이를 부모에게 전달하기 위해 iframe 페이지의 트리거를 사용하는 것입니다 window.onload(NOT domready, 이미지를로드하는 데 시간이 걸릴 수 있음).

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

그러면 parent.resizeIframe다음과 같이 보입니다.

function resizeIframe(newHeight)
{
    document.getElementById('blogIframe').style.height = parseInt(newHeight,10) + 10 + 'px';
}

예, 당신은 페이지가 완전히 렌더링되면 번거로운 contentdocument대 조작 없이 트리거되는 강력한 크기 contentWindow조정기가 있습니다. :)

물론 이제 사람들은 먼저 기본 높이에서 iframe을 볼 수 있지만 처음에는 iframe을 숨기고 '로드 중'이미지 만 표시하면 쉽게 처리 할 수 ​​있습니다. 그런 다음 resizeIframe함수가 시작되면 로딩 이미지를 숨기고 가짜 Ajax 모양의 iframe을 표시하는 두 줄을 추가로 넣습니다.

물론 이것은 동일한 도메인에서만 작동하므로이 항목을 포함하기 위해 프록시 PHP 스크립트가 필요할 수 있습니다. 일단 거기에 가면 PHP를 사용하여 블로그의 RSS 피드를 사이트에 직접 삽입하는 것이 좋습니다.


JavaScript로이 작업을 수행 할 수 있습니다.

document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";

IFRAME 콘텐츠를 맞추는 것은 Google 에서 쉽게 찾을 수 있습니다 . 다음은 한 가지 해결책입니다 .

<script type="text/javascript">
    function autoIframe(frameId) {
       try {
          frame = document.getElementById(frameId);
          innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
          objToResize = (frame.style) ? frame.style : frame;
          objToResize.height = innerDoc.body.scrollHeight + 10;
       }
       catch(err) {
          window.status = err.message;
       }
    }
</script>

이것은 당연히 도메인 간 문제를 해결하지 못합니다. document.domain이러한 사이트가 같은 위치에 있으면 설정 이 도움이 될 수 있습니다. 나는 당신이 임의의 사이트를 iframe-ing한다면 해결책이 없다고 생각합니다.


Firefox 3.6, Safari 4.0.4 및 Internet Explorer 7에서 작동하는 MooTools를 사용하는 문제에 대한 해결책은 다음과 같습니다.

var iframe_container = $('iframe_container_id');
var iframe_style = {
    height: 300,
    width: '100%'
};
if (!Browser.Engine.trident) {
    // IE has hasLayout issues if iframe display is none, so don't use the loading class
    iframe_container.addClass('loading');
    iframe_style.display = 'none';
}
this.iframe = new IFrame({
    frameBorder: 0,
    src: "http://www.youriframeurl.com/",
    styles: iframe_style,
    events: {
        'load': function() {
            var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
            var h = this.measure(function(){
                return innerDoc.body.scrollHeight;
            });            
            this.setStyles({
                height: h.toInt(),
                display: 'block'
            });
            if (!Browser.Engine.trident) {
                iframe_container.removeClass('loading');
            }
        }
    }
}).inject(iframe_container);

"loading"클래스의 스타일을 지정하여 iframe 컨테이너 중간에 Ajax 로딩 그래픽을 표시합니다. 그런 다음 Internet Explorer 이외의 브라우저의 경우 콘텐츠로드가 완료되면 전체 높이 IFRAME이 표시되고로드 그래픽이 제거됩니다.


아래는 내 onload이벤트 핸들러입니다.

jQuery UI 대화 상자 에서 IFRAME을 사용합니다 . 용도에 따라 약간의 조정이 필요합니다. 이것은 Internet Explorer 8 및 Firefox 3.5에서 나에게 (당분간) 트릭을 수행하는 것 같습니다. 추가 조정이 필요할 수 있지만 일반적인 아이디어는 명확해야합니다.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

@SchizoDuckie의 대답은 매우 우아하고 가볍지 만 Webkit의 scrollHeight 구현이 없기 때문에 ( 여기 참조 ) Webkit 기반 브라우저 (Safari, Chrome, 다양한 및 잡다한 모바일 플랫폼)에서 작동하지 않습니다.

이 기본 아이디어가 Gecko 및 Trident 브라우저와 함께 Webkit에서 작동하려면

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

<body onload='parent.resizeIframe(document.body.offsetHeight)'>

모든 것이 동일한 도메인에있는 한 이것은 매우 잘 작동합니다.


I just spent the better part of 3 days wrestling with this. I'm working on an application that loads other applications into itself while maintaining a fixed header and a fixed footer. Here's what I've come up with. (I also used EasyXDM, with success, but pulled it out later to use this solution.)

Make sure to run this code AFTER the <iframe> exists in the DOM. Put it into the page that pulls in the iframe (the parent).

// get the iframe
var theFrame = $("#myIframe");
// set its height to the height of the window minus the combined height of fixed header and footer
theFrame.height(Number($(window).height()) - 80);

function resizeIframe() {
    theFrame.height(Number($(window).height()) - 80);
}

// setup a resize method to fire off resizeIframe.
// use timeout to filter out unnecessary firing.
var TO = false;
$(window).resize(function() {
    if (TO !== false) clearTimeout(TO);
    TO = setTimeout(resizeIframe, 500); //500 is time in miliseconds
});

The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.

var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
    // Setting the content window's resize function tells us when we've changed the height of the internal document
    // It also only needs to do what onload does, so just have it call onload
    dFrame.contentWindow.onresize = function() { dFrame.onload() };
    dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
    dFrame.onload();
}

This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)


Try this, you can change for even when you want. this example use jQuery.

$('#iframe').live('mousemove', function (event) {   
    var theFrame = $(this, parent.document.body);
    this.height($(document.body).height() - 350);           
});

Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.

In terms of the height, you could also try height=100% on the iframe tag.

참고URL : https://stackoverflow.com/questions/525992/resize-iframe-height-according-to-content-height-in-it

반응형