【问题标题】:Create iframes from original page content with jQuery使用 jQuery 从原始页面内容创建 iframe
【发布时间】:2012-09-07 19:46:12
【问题描述】:

我正在尝试将整个页面动态“重写”为一组 iframe。我想要一个位于底部 iframe 的音乐播放器栏,并在其上方/后面的 iframe 中“重写”原始页面。几乎就像SMC player。我觉得我很接近,但我是一个 jQuery 新手。所以任何指针都将事先不胜感激。

这是创建无法正常工作的 iframe 的主要部分。

var oldpage =  "<html>" + $("html").html() + "</html>";
$('body').html( "<iframe frameborder='0' id='content' allowtransparency='true' name='content'></iframe>" );
$('#content').contents().find('html').html(oldpage);
$('body').append("<iframe id='stratus' allowtransparency='true' frameborder='0' scrolling='0'>");

我正在尝试在第 1 行加载整个原始 html。然后创建 iframe 并尝试将 oldbody 变量注入新的 iframe #content。 iframe 已创建,但 #content iframe 的正文为空白。

【问题讨论】:

    标签: javascript jquery html iframe


    【解决方案1】:

    我不知道为什么,但是你不能替换整个 HTML 元素,只能替换它的内容:

    // create raw frame
    var frame = $('<iframe id="maincontent" style="position:absolute; top: 0; left: 0; width: 50%; height: 50%;"><html></html></iframe>');
    
    // store a copy of current document contents
    var copiedHead = $('head').clone();
    var copiedBody = $('body').clone();
    
    // empty the current document
    $(':not(iframe) body *').remove();
    
    // load the copy into the frame;
    // it's not possible to replace the whole HTML element;
    // using plain JS DOM function here, since jQuery would strip out any SCRIPT and STYLE tags
    frame.load(function(){
        $(this).contents().find('html')[0].replaceChild(copiedHead[0] , $(this).contents().find('head')[0]);
        $(this).contents().find('html')[0].replaceChild(copiedBody[0] , $(this).contents().find('body')[0]);
    }).appendTo('body');
    

    【讨论】:

    • 工作就像一个魅力,谢谢!奇怪的是你不能选择整个 html 内容。
    • 现在我还有另一个问题。也许我会开始一篇新文章,但是当我单击#content iframe 中的链接时,它只会重新加载主页并且不会跟随链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2012-05-27
    • 2014-10-02
    • 2015-08-09
    • 1970-01-01
    • 2014-04-13
    • 2021-09-02
    相关资源
    最近更新 更多