【问题标题】:Show DIV only when iframe page is loaded仅在加载 iframe 页面时显示 DIV
【发布时间】:2013-02-28 03:00:13
【问题描述】:

我在 DIV 中有一个 iframe 页面,我只希望在 iframe 页面加载/可用后显示该 DIV。如果 iframe 页面未加载/不可用,则根本不显示该 DIV。

我写了一些 JS,但是它并没有像我预期的那样工作,无论 iframe 页面是否可用,DIV 仍然显示。

代码:

<div class="ad-container" style="display:none">
   <iframe src="//oonagi.org" border="0" scrolling="no" allowtransparency="true" width="500" height="300"></iframe>
</div>

var adContainer = $('.ad-container');
// check if ad container exist
if(adContainer.length > 0) {
  // only show ad once iframe page is loaded
  adContainer.find('iframe').load(function() {
    adContainer.css('display', 'block');
  });
}

【问题讨论】:

  • 无论页面是否可用,仍然会加载 iframe。您需要在 iframe 中有一个控件来通知父窗口。
  • 不幸的是,我对 iframed 页面没有权限。没有其他解决办法吗?
  • 一种解决方法是创建一个对 url 的 ajax 请求,如果返回成功则更新 div 显示。但这不是一个好的解决方案,因为会向第三方网站发出两个请求。

标签: javascript jquery iframe


【解决方案1】:

您应该在document.ready 更改 iframe src 以使其触发您的 iframe 加载事件。您可以试试这个:

$(document).ready(function() {

    $('#frame').bind('load', function() { //binds the event
        $('#ad-container').show();
    });

    var newSrc = $('#frame').attr('src') + '?c=' + Math.random(); //force new URL
    $('#frame').attr('src', newSrc); //changing the src triggers the load event

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多