【问题标题】:Always open a html page in fancyBox iframe总是在 fancyBox iframe 中打开一个 html 页面
【发布时间】:2014-07-15 00:58:08
【问题描述】:

我使用Fancybox在fancybox中显示外部html页面,例如:在page1我设置了一个链接,它在fancyboxiframe模式下打开page2,效果很好。

问题是:

如果有人尝试输入 page2 的 URL,是否有可能让 page2 始终从 page1 中打开,而不是像普通页面那样在浏览器窗口中打开?

【问题讨论】:

    标签: javascript jquery iframe fancybox


    【解决方案1】:

    是的,这是可能的。

    所以第一页 (parent.html) 将通过类似

    的链接在 fancybox 中打开第二页 (iframed.html)
    <a id="openIframe" class="fancybox" href="iframed.html">Open page inside fancybox iframe</a>
    

    注意,我为将打开 iframed 页面的链接设置了 IDclass

    然后是每个页面的脚本:

    parent.html

    父页面应该有两个特定的代码:

    • 初始化fancybox的代码
    • 检测hash 何时出现在URL 中的代码,以便它可以触发fancybox

    所以:

    // initialize fancybox
    $(".fancybox").fancybox({
        // API options
        type: "iframe" //<== at least this one
    });
    
    if (window.location.hash) {
        // detect if URL has hash and trigger fancybox
        $(window.location.hash + ".fancybox").trigger("click");
        // remove hash after fancybox was opened 
        // two methods to cover most browsers
        if (navigator.userAgent.match(/msie/i)) {
            var loc = window.location.href;
            index = loc.indexOf('#');
            if (index > 0) {
                window.location = loc.substring(0, index);
            }
        } else {
            history.pushState("", document.title, window.location.pathname);
        };
    };
    

    那么第二页 (iframed.html) 应该有一个代码,用于检测 自身 是否已在 iframe 内打开(我们的 fancybox iframe案子)。

    如果不是,它应该重定向到父页面,定位打开fancybox的链接的ID:

    iframed.html

    if (self == top) {
        window.location.href = "parent.html#openIframe";
    };
    

    注意如果页面没有在 iframe 中打开,self == top 将返回 true,因此它会重定向到父级。

    查看JSFIDDLE(并尝试在新窗口/标签中打开链接)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 2014-02-16
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多