【问题标题】:Trouble triggering actions on iframe load/ready event (jquery)无法触发 iframe 加载/就绪事件的操作(jquery)
【发布时间】:2012-02-28 21:04:24
【问题描述】:

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

我想:

  • 由于两个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();
    });
}); 
//--> 

现在麻烦了:

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

页面加载时,第一次:

页面加载,第二次:

提交后:

【问题讨论】:

  • 编辑了一些东西,因为我意识到我没有在 slideshow.php 中包含 js 文件 ^^U 但是其他问题仍然存在。
  • 您是否考虑过将 jQuery 添加到 iframe 页面并在那里使用一个小脚本来触发父级中的自定义“loadiframe”事件?

标签: jquery iframe height


【解决方案1】:

这是我的 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); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    • 2011-07-20
    相关资源
    最近更新 更多