无法触发iframe加载/就绪事件(jquery)上的操作

时间:2012-02-07 12:23:23

标签: jquery iframe height

我有一个管理面板,我想上传与产品相关的图片。我已将上传内容分隔为iframe,并将图片预览分隔为另一个iframe,因此每次提交表单时我都不必重新加载整个页面。现在它看起来像这样(添加边框作为参考):

enter image description here

我想:

  • 由于两个iframe的高度都是可变的(它取决于第二个中的图片数量,并且在上传完成后在拳头上显示反馈消息):设置iframe的高度以适合高度身体内容。
  • 提交上传表单后显示进度条gif,并在框架加载完成后隐藏它。
  • 在表单提交后上传表单完成加载后重新加载预览框架,以便显示已添加的新图片。

我的代码现在看起来像这样:

HTML:

<p>
Subir imagen:
<span class="loading_bar"></span><br />
<iframe name="upload_iframe" class="upload_iframe" src="upload.php" scrolling="no"></iframe>
</p>

<p>
<iframe name="slideshow_iframe" class="slideshow_iframe" src="slideshow.php" scrolling="no"></iframe>
</p>

使用Javascript:

//<!--
$(document).ready(function(){
    // ------------------ UPLOAD ------------------

    // On any frame load
    $("iframe").load(function() {
        // Change frame's height to be the same as the contents body's height
        var iframe_height = $(this).contents().find('body').height();
        $(this).height(iframe_height);
        // Control point
        alert("Frame: "+$(this).attr("class")+" | Content height: "+iframe_height+" | Frame height: "+$(this).height());
    });

    // On "iframe_upload" load
    $("iframe.upload_iframe").load(function() {
        // Hide progress bar
        $(this).prev("span.loading_bar").hide();
        // Reload "iframe_slideshow"
        $("iframe.upload_slideshow").attr("src",$("iframe.upload_slideshow").attr("src"));
    });

    // On "select file" change
    $(".upload_form_upload").change(function() {
        var parent_element = "#"+$(this).closest("form").attr("id");
        // Show progress bar
        $(parent_element+" span.loading_bar", parent.document).show();
        // Submit upload form
        $(this).closest("form").submit();
    });
}); 
//--> 

现在麻烦了:

  • 负载下的操作永远不会触发,不会在首次加载网站时,也不会在提交表单时触发。
  • 如果我为.ready()更改了.load(),当网站被加载到$(“iframe”)内的所有内容时.ready(){触发每个iframe两次以及$ if下面的内容(“iframe.upload_iframe”) ).ready()永远不会被触发。即使我接到警报,也没有设置新的高度。
  • 这是我从“控制点”下的警报中得到的:

在页面加载时,第一次:

enter image description here

页面加载,第二次:

enter image description here

提交后:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是我的iframe调整大小脚本,可以跨浏览器工作。希望它有所帮助!

//get iframe
var iframe = $('iframe')[0];
//get iframe body (IE?)        
var iframeBody = (iframe.contentDocument) ? iframe.contentDocument.body : iframe.contentWindow.document.body;
//works out the new height by matching the offsetHeight and scrollHeight
var height = (iframeBody.scrollHeight < iframeBody.offsetHeight) ? iframeBody.scrollHeight : iframeBody.offsetHeight;
//sets the new height on the iframe
$(iframe).height(height);