【问题标题】:Print IFrame in ie10 doesn't work在 ie10 中打印 IFrame 不起作用
【发布时间】:2013-10-01 07:54:37
【问题描述】:

我正在尝试在 IE10 中打印动态创建的 iframe。它既不抛出错误也不工作。下面是我的代码。

function PrintVisitSlip() {
    var f = document.getElementById('frmPrintVisitSlip');
    var ifrm = document.createElement("iframe");
    ifrm.src = 'about:blank';
    ifrm.style.display = "none";
    document.body.appendChild(ifrm);
    var _styleCSS = '<style type="text/css">p{border-bottom: white;}.Head{font-size: 9pt;font-weight: bold;}'
        + 'td{border-bottom: 1px solid black;height: 8px;padding: 0px 0px 0px 0px;margin: 0 0 0 0;font-size: 7pt;padding: 1px 0 1px 0;}'
        + '.LC{width: 125px;text-align: left;padding-left: 4px;}.RC{width: 21px;text-align: right;padding-right: 3px;}'
        + '.LC1{width: 80px;text-align: left;padding-left: 4px;font-size: 6.5pt;}.RC1{width: 18px;text-align: right;}</style>';
    ifrm.contentWindow.document.open('text/html', 'replace');
    ifrm.contentWindow.document.write(_styleCSS + f.outerHTML);
    ifrm.contentWindow.document.close();
    var iw = ifrm.contentWindow || ifrm;
    iw.focus();
    iw.print();
    return false;
}

此代码在 chrome 中运行良好。但在 IE10 中,单击打印按钮时我看不到任何打印窗口。

【问题讨论】:

  • 你的脚本能没有错误吗?也许你有一个特定于 IE 的错误,这就是你没有打印出来的原因。按 F12 打开 webdev 并转到 Console 以查看任何脚本错误。

标签: javascript html internet-explorer iframe printing


【解决方案1】:

iframe的文档的readyStatecomplete时尝试打印,因为open.write在IE下是异步的。此外,ifrm.style.display = "none" 会阻止打印框架,因此会打印整个窗口。

以下代码已通过 IE10 验证。它可能不适用于其他浏览器。

<!DOCTYPE html>
<head>
    <title>main</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <script>
        function Go() {
            var ifrm = document.createElement("iframe");

            ifrm.src = 'about:blank';
            ifrm.style.borderWidth = 0;
            ifrm.style.width = 0;
            ifrm.style.height = 0;

            document.body.appendChild(ifrm);

            ifrm.contentWindow.document.open("text/html", "replace");

            ifrm.contentWindow.document.onreadystatechange = function () {
                if (ifrm.contentWindow.document.readyState === "complete") {
                    ifrm.contentWindow.document.body.onafterprint = function () {
                        ifrm.removeNode(true);
                    }
                    ifrm.contentWindow.document.body.focus();
                    ifrm.contentWindow.print();
                }
            }

            ifrm.contentWindow.document.write("<b>Hello</b>, world!");
            ifrm.contentWindow.document.close();
        }
    </script>
</head>
<body>
    <button onclick="Go()">Go</button>
</body>

【讨论】:

  • 我不明白您的编辑。您是否将代码更新为正确的,还是留下了不正确的代码?这令人困惑。为什么有两段 Javascript 看起来几乎一样?
  • @Richard,我已经清理了答案。
猜你喜欢
  • 2013-12-02
  • 2013-11-13
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2015-04-12
相关资源
最近更新 更多