Fancybox iframe with content encoded in js on laun

2019-03-01 01:59发布

问题:

Thanks to this answer, I have a way of launching a fancybox iframe on page-load: http://www.casedasole.it/fancybox/A.html

This answer shows how to open a fancybox iframe whose content is encoded in javascript in the page that launches the iframe: http://www.casedasole.it/fancybox/B.html

Is there some way of having B do what A does - i.e. launch itself on page-load?

NB: The hidden div approach (see here) won't work because I need to be able to navigate within the iframe once opened.

回答1:

Just do :

var myContent = "..."; // html as option "B"

jQuery(document).ready(function ($) {
    $.fancybox({
        // API options as "B"
        // build the iframe
        content: '<iframe id="myFrame" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" src="about:blank"></iframe>',
        afterShow: function () {
            var oIframe = document.getElementById('myFrame');
            var iframeDoc = (oIframe.contentWindow.document || oIframe.contentDocument);
            iframeDoc.open();
            iframeDoc.write(myContent);
            iframeDoc.close();
        }
    });
}); // ready

See JSFIDDLE

Notice the myContent variable contains the full html structure, including DOCTYPE, <html>, <head> an <body> sections. Although it's not mandatory, it will give you more control over the settings of your initial (iframed) page.

Also notice in my jsfiddle I separated the base content (html basic structure) from the custom content (the <div> as in your example) for tidiness purposes ;)

Refs :

  • Option A : http://jsfiddle.net/8qp0Lr3z/1/
  • Option B : http://jsfiddle.net/qVrLr/