[英]trying to print iframe content but print the whole page instead
我已经在html页面中动态创建的iframe和带有单击事件的打印按钮,可以单击以打印iframe的内容,但是不幸的是,它可以打印整个页面,但是经过长时间的搜索,我发现了一些解决方案,例如在fire print事件之前专注于iframe,但是似乎无法在IE和MS Edge上运行,但在Chrome上运行,唯一适用于我的解决方案是打开新窗口并在其中复制iframe外层HTML,然后在新窗口中加载内容后触发print事件,然后立即关闭新窗口用户执行操作以打印或取消后,但此解决方案看起来对用户不友好,因此是否有任何解决方案可在IE和Edge中打印iframe内容
<html>
<head>
<title>IFrame Printing Issue</title>
<script type="text/javascript">
var g_iFrame;
function onLoad()
{
g_iFrame = document.createElement("iframe");
g_iFrame.id = "testFrame";
var style = g_iFrame.style;
style.border = "1px solid black";
style.width = "300px";
style.height = "200px";
document.body.appendChild(g_iFrame);
}
function setIFrameSrc()
{
g_iFrame.src = "Test.htm";
}
function printIFrameContent()
{
window.frames["testFrame"].contentWindow.focus();
window.frames.testFrame.contentWindow.print();
}
</script>
</head>
<body onload="onLoad();">
<button type="button" onclick="setIFrameSrc();">Set IFrame Src</button>
<br />
<button type="button" onclick="printIFrameContent();">Print IFrameContent</button>
<br />
<div style="border: 1px solid black; width: 300px; height: 200px;">
This is to test printing the content of an IFrame whose src is set dynamically.
</div>
</body>
</html>
您可以先检查用户代理是否为IE:
function printIFrameContent()
{
var ua = window.navigator.userAgent;
var msie = ua.indexOf ("MSIE ");
var iframe = document.getElementById("testFrame");
if (msie > 0) {
iframe.contentWindow.document.execCommand('print', false, null);
} else {
iframe.contentWindow.print();
}
}
在SO上引用了类似的答案: https : //stackoverflow.com/a/19639241/1500851
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.