如何使用JavaScript实现打印场景下表格元素固定不偏移
解决方案
你遇到的问题是表格单元格默认垂直居中对齐导致的,无需使用position: fixed(该属性会让元素脱离文档流,必然破坏表格布局),只需要在打印样式中补充vertical-align: top规则即可实现所有单元格内容顶部对齐。
修改后的完整代码如下:
function printDiv() { var divToPrint = document.getElementById('table'); var htmlToPrint = '' + '<style type="text/css">' + // 可选:合并边框避免重复显示,可根据需求保留或删除 'table { border-collapse: collapse; width: 100%; }' + 'table th, table td,table tr {' + 'font-family:B Nazanin;'+ 'border:0.1em solid #000;' + 'text-align:center;' + 'vertical-align: top;' + // 新增规则,强制单元格内容顶部对齐 'font-size:14px;' + 'padding:0.2em;' + '}' + '</style>'; htmlToPrint += divToPrint.outerHTML; newWin = window.open(""); newWin.document.write(htmlToPrint); newWin.print(); newWin.close(); }
如果需要实现打印时表头固定在每一页顶部,可以额外补充如下打印样式规则:
@media print { thead th { position: sticky; top: 0; background-color: #ffffff; } }
问题效果参考:
内容的提问来源于stack exchange,提问作者stoo frisat
相关产品推荐
相关产品推荐

