gpt4 book ai didi

javascript - 将 JavaScript 和 HTML 添加到 IFRAME,并将 IFRAME 打印到打印机

转载 作者:行者123 更新时间:2023-11-30 17:41:21 25 4
gpt4 key购买 nike

有多个帖子涉及这些主题的一部分,但没有一个将它们放在一起。

在给定的页面上,我希望创建一个新的 IFRAME,向其中添加一些 JavaScript 以将页面打印到打印机,并向其中添加一些 HTML 以进行打印。

以下是我在 http://jsbin.com/UDUCADI/2/ 上的现场演示尝试.它打印,但打印父页面而不是 IFRAME。

如何只打印 IFRAME?

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Print IFRAME</title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#printIt').click(function(){
var iframe = $('<iframe>');
var script = document.createElement("script");
script.type = "text/javascript";
script.text = "window.print()";
iframe[0].appendChild(script);
iframe.appendTo('body');
var iframeDocument=$(iframe[0].contentWindow.document);
iframeDocument.find('body').html($('#stuffToPrint').html());
})
});
</script>
</head>
<body>
<button id="printIt">Print</button>
<div id="stuffToPrint">
<p>Print this text!</p>
<img alt="And print this image" src="dropdown_arrow_blue.gif">
</div>
<div>Don't print this!</div>
</body>
</html>

最佳答案

已编辑

实际上有一些错误。其中之一是您正在混合使用 jQuery 和 DOM api。第二个是将脚本标记添加到 iframe 的主体,然后再次设置主体的 HTML,覆盖脚本标记。第三:您正在使用 script.text,它应该是 script.innerHTML。

$(function () {
$('#printIt').click(function(){
var iframe = document.createElement('iframe');
document.body.appendChild(iframe)
iframe.contentWindow.document.body.innerHTML = $('#stuffToPrint').html();
var script = document.createElement("script");
script.innerHTML = "window.print()";
iframe.contentWindow.document.body.appendChild(script);
})
});

工作版本:http://jsbin.com/UDUCADI/5/

关于javascript - 将 JavaScript 和 HTML 添加到 IFRAME,并将 IFRAME 打印到打印机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21027014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com