根据内容高度调整iframe高度

时间:2009-02-08 16:36:25

标签: php javascript ajax iframe

我在我的网站上打开我的博客页面。问题是我可以给iframe一个宽度,但高度应该是动态的,这样iframe中就没有滚动条了,它看起来像一个页面......

我尝试过各种JavaScript代码来计算内容的高度,但所有这些代码都会出现访问被拒绝权限错误,并且没用。

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

我们可以使用Ajax来计算高度还是使用PHP?

10 个答案:

答案 0 :(得分:60)

直接回答你的两个子问题:不,你不能用Ajax做这个,也不能用PHP计算它。

我过去所做的是使用window.onload中的iframe页面的触发器(非domready,因为可能需要一段时间才能加载图片)来传递页面的正文父母的身高。

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

然后parent.resizeIframe看起来像这样:

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

Et瞧,你有一个强大的缩放器,一旦页面完全渲染就会触发,没有讨厌的contentdocument vs contentWindow摆弄:)

当然,现在人们会首先看到你的iframe处于默认高度,但这可以通过首先隐藏你的iframe并显示“加载”图像来轻松处理。然后,当resizeIframe函数启动时,在其中添加两行以隐藏加载图像,并显示该伪造Ajax外观的iframe。

当然,这只能在同一个域中运行,所以你可能想要一个代理PHP脚本来嵌入这些东西,一旦你去那里,你也可以直接将你博客的RSS源直接嵌入你的网站PHP。

答案 1 :(得分:8)

您可以使用JavaScript执行此操作。

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

答案 2 :(得分:4)

安装IFRAME内容对find on Google来说很容易。这是one solution

<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可能会有所帮助。如果你是随机网站,我认为没有解决方案。

答案 3 :(得分:2)

这是使用MooTools解决问题的解决方案,该解决方案适用于Firefox 3.6,Safari 4.0.4和Internet Explorer 7:

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并删除加载图形。

答案 4 :(得分:0)

以下是我的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);
    }
};

答案 5 :(得分:0)

诀窍是从外部脚本获取所有必需的iframe事件。例如,您有一个使用document.createElement创建iFrame的脚本;在同一个脚本中,您可以暂时访问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();
}

这是有效的,因为dFrame保留在这些函数的范围内,使您可以从框架范围内访问外部iFrame元素,从而可以查看实际文档高度并根据需要进行扩展。这个例子可以在firefox中使用,但不在其他地方;我可以给你解决方法,但你可以弄清楚其余部分;)

答案 6 :(得分:0)

@ SchizoDuckie的答案非常优雅和轻量级,但由于Webkit缺乏scrollHeight的实现(请参阅here),因此无法在基于Webkit的浏览器(Safari,Chrome,各种各样的移动平台)上运行。

对于使用Gecko和Trident浏览器的Webkit的基本思想,只需要替换

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

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

只要一切都在同一个域上,这就非常有效。

答案 7 :(得分:0)

试试这个,即使你想要也可以改变。这个例子使用jQuery。

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

答案 8 :(得分:0)

我只花了3天的时间来与这个摔跤。我正在开发一个应用程序,在保持固定页眉和固定页脚的同时将其他应用程序加载到自身中。这就是我想出的。 (我也成功地使用了EasyXDM,但稍后将其用于使用此解决方案。)

确保在DOM中存在<iframe>之后运行此代码。将它放入拉入iframe(父级)的页面。

// 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
});

答案 9 :(得分:-3)

尝试在iframe代码上使用scrolling=no属性。 Mozilla还有一个overflow-xoverflow-y CSS属性,您可以查看。

就高度而言,您还可以在iframe代码上尝试height=100%

相关问题