点击打印按钮并触发打印功能后,应用程序冻结



我在应用程序中实现打印功能时遇到问题。我有一个javascript函数,当我点击print按钮时,它应该打印特定div的内容。每当我点击打印按钮时,打印功能就会工作,但会导致主窗口冻结。我也试着添加了一个window.close,但似乎不起作用。关于如何解决这个问题的任何想法,或者关于如何打印特定内容的任何替代方案。我尝试的任何其他方法最终都会将该div的所有元素向左移动。

下方的功能

export const printDiv = (id: string) => {
let printContents = document.getElementById(id).innerHTML
let originalContents = document.body.innerHTML
document.body.innerHTML = printContents
window.print()
document.body.innerHTML = originalContents
}

HTML

<!DOCTYPE html>
<html>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<button onClick={() => printDiv("print")}>Print</button>
<table style="width:100%" id="print">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
<p>This portion should not be included in the print page</p>
</body>
</html>

谢谢。

这对我有效…也许你遇到了不同的问题。。。

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border:1px solid black;
}
</style>      
<script type="text/javascript">
printDiv = (id) => {
let originalContents = document.body.innerHTML
let printContents = document.getElementById(id).innerHTML
document.body.innerHTML = printContents
window.print()
document.body.innerHTML = originalContents
// window.close()
}

</script>
</head>
<body>
<button onclick="printDiv('print')">Print</button>
<table style="width:100%" id="print">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
<p>This portion should not be included in the print page</p>
</body>
</html>

最新更新