【问题标题】:Show loading gif every time iframe loads a page每次 iframe 加载页面时显示加载 gif
【发布时间】:2015-08-23 19:10:22
【问题描述】:

每当在 iframe 中加载新页面时,我希望在父窗口中的 iframe 上显示加载 GIF。我已经看到此类问题的解决方案,但它们似乎只适用于默认页面。一旦用户在 iframe 中离开该页面,加载 GIF 将不会显示。

这可能使用 JavaScript 或 jQuery 吗?我在 Stack Overflow 上尝试了其他解决方案,但没有成功。

【问题讨论】:

  • 很难理解您的问题。您是什么意思“当用户离开 iframe 中的页面时”?哦,人们会问你“你做了什么”或可能的“告诉我们你尝试了什么”?
  • “当用户离开 iframe 中的页面时”也就是当用户点击离开 iframe 的默认页面时。我尝试过的是 Stack Overflow 上已经针对类似问题的解决方案。例如:stackoverflow.com/questions/12136788/…

标签: javascript jquery html css frontend


【解决方案1】:

如果您的框架将始终与父窗口位于同一域中,您可以在 iframe contentWindow 上注册 onbeforeunload 事件处理程序以检测导航离开。

例子:

var iframe = // create or get iframe, make sure no src parameter at first
var unload = function(){
    // show loading gif here
};

var load = function(){
    // hide loading gif here

    iframe.contentWindow.onbeforeunload = unload;
    iframe.onload = load;
};

unload();
iframe.onload = load;
iframe.src = "your url here";

小提琴:http://jsfiddle.net/qnausxac/1/

注意:不要使用类似的东西在 iframe 中注册 onbeforeunload 事件

window.onbeforeunload = function(){/* ... */} // BAD

这将覆盖您的父事件处理程序。如果您需要检测 iframe 中的事件,请与父级设置某种回调。

【讨论】:

    【解决方案2】:

    我将从 iframes 开始,其中有空的 src 并将目标存储在另一个属性中

    <div class="holder">
        <div class="gif-hidden"></div>
        <iframe class="myframe" src="" attr-link="https://google.com/" attr-first="true"></iframe>
    </div>
    

    然后当页面加载成功后,启动动画并设置src

    .gif-hidden 应该具有display:noneopacity:0 属性,而.gif 是可见的。

    $('.gif-hidden').removeClass('gif-hidden').addClass('gif');
    $('.myframe').attr('src',$('.myframe').attr('attr-link'));
    

    还添加一个事件侦听器以在第一次加载 iframe 时禁用动画

    $('.myframe').load(function(){
         if($(this).attr('attr-first') == "true")
         {
             $(this).attr('attr-first','false');
             $(this).prev().hide();
         }
    } 
    

    未测试,但应该可以工作。

    【讨论】:

    • 我不认为每次加载 iframe 中的页面时都会出现这种情况,对吗?
    • 您要求的解决方案只在第一次加载时显示动画。 “一旦用户在 iframe 中离开该页面,加载 GIF 将不会显示。”
    • 不,我的意思是在尝试其他解决方案时,加载的 GIF 不会出现。我想要它出现。
    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多