我想做的是在不破坏任何样式或 javascript 的情况下将完整的网站包装在 iframe
中。
这是我试过的:
var $frame = $('<iframe />').css({
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%'
}).appendTo('body');
$('head').children().appendTo($frame.contents().find('head'));
$('body').children().not($frame).appendTo($frame.contents().find('body'));
参见 http://jsfiddle.net/gUJWU/3/
这在 Chrome 中运行良好。
Firefox 似乎吞下了整个页面。
Internet Explorer(参见 http://jsfiddle.net/gUJWU/3/show/)确实创建了 iframe
,但没有向其中移动任何内容。
这种方法是否有可能跨浏览器工作?
最佳答案
在 IE 中,文档不会被推断和自动创建,因此您需要在访问它之前实际创建它:
var $frame = $('<iframe />').css({
position: 'fixed',
top: 0,
left: 0,
width: '100%',
height: '100%'
}).appendTo('body');
var doc = $frame[0].contentDocument || $frame[0].contentWindow.document;
doc.open();
doc.write("<!DOCTYPE html><html><head><title></title></head><body></body></html>");
doc.close();
$('head').children().appendTo($frame.contents().find('head'));
$('body').children().not($frame).appendTo($frame.contents().find('body'));
演示: http://jsfiddle.net/XAMTc/show/
这似乎在 IE8/9 中有效,至少在最近的 Firefox 和 Chrome 中有效。
我发现问题的方法是通过 console.log
ging $frame.contents().find('head').length
,它在 0浏览器。
关于javascript - 将整个文档移动到 iframe 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259499/