繁体   English   中英

使用window.open()方法在打印预览页面内添加javascript

[英]Add javascript inside print preview page using window.open() method

在这里有一个样本小提琴,这里有一个打印预览按钮。 点击该按钮后,它将打开一个新的弹出窗口,该窗口创建为

function printpage() {
    var data = '<table border="1" cellspacing="0"><tr><td colspan="4">Sample Report</td></tr>' + document.getElementsByTagName('table')[0].innerHTML + '</table>';
    data += '<br/><button onclick="window.print()"  class="noprint">Print the Report</button>';
    data += '<style type="text/css" media="print"> .noprint {visibility: hidden;} </style>';
    myWindow = window.open('', '', 'width=800,height=600');
    myWindow.innerWidth = screen.width;
    myWindow.innerHeight = screen.height;
    myWindow.screenX = 0;
    myWindow.screenY = 0;
    myWindow.document.write(data);
    myWindow.focus();
}

使用google chrome开发人员工具查看其源代码时,我可以获得以下代码。

<html>
<head></head>
<body>
<table border="1" cellspacing="0"><tbody><tr><td colspan="4">Sample Report</td></tr>
    </tbody>
    <tbody>
    <tr><th>Sl.No</th><th>Value 1</th><th>Value 2</th><th>Value 3</th></tr>
    <tr><td>1</td><td>5</td><td>0</td><td>2</td></tr>
    <tr><td>2</td><td>7</td><td>0</td><td>4</td></tr>
    <tr><td>3</td><td>1</td><td>0</td><td>10</td></tr>
    <tr><td>4</td><td>8</td><td>0</td><td>3</td></tr>
    <tr><td>5</td><td>13</td><td>0</td><td>6</td></tr>
</tbody></table><br>
<button onclick="window.print()" class="noprint">Print the Report</button><style type="text/css" media="print"> .noprint {visibility: hidden;} </style>
</body>
</html>

是否可以在该弹出窗口中添加一些额外的javascript / jquery代码?

您可以像这样向data变量添加脚本:

var data = '<script>/* CODE */ <\/script>' +
    '<table ...>' +
           :
    '<style...>';

字符串中的结束script标记必须以某种方式破坏,以免它显示为原义</script> 如果确实如此,则在找到标记后,脚本将中断。

另外,您还需要注意,脚本字符串中的引号不会破坏字符串。 必要时使用" s并使用反斜杠转义'

实际上,有更多优雅的方法可以设置页面(或页面的一部分)的样式以进行打印,例如,您可以使用Media Queries单独的样式表链接 (请参阅media )以样式化打印。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM