You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在打印前隐藏表格最后两列?(附现有打印实现代码)

如何在打印前隐藏表格最后两列?(附现有打印实现代码)

嗨,别担心,这事儿不难,我给你准备了两种简单的实现方式,直接替换你原来的脚本就行,还会给你解释每一步的作用~

方法一:通过DOM操作移除最后两列(不影响原页面表格)

这种方法是先复制一份你要打印的表格,然后移除副本里的最后两列,再拿去打印,完全不会改动原页面的表格内容:

<script type="text/javascript">
function printPage(){
    // 获取原表格并深克隆一份,避免修改原页面的表格
    const originalTable = document.getElementsByTagName('table')[0];
    const clonedTable = originalTable.cloneNode(true);

    // 遍历克隆表格的每一行,移除最后两个单元格(包括表头行)
    const allRows = clonedTable.querySelectorAll('tr');
    allRows.forEach(row => {
        // 先删最后一个单元格
        if (row.lastElementChild) row.removeChild(row.lastElementChild);
        // 再删倒数第二个单元格
        if (row.lastElementChild) row.removeChild(row.lastElementChild);
    });

    // 把处理好的克隆表格转成HTML字符串
    const tableData = clonedTable.outerHTML;

    const t='Tabella configurazione slot giorni e ore. &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;';
    const data = '<button onclick="window.print()">Print this page</button>'+tableData;   
    
    myWindow=window.open('','','width=800,height=600,left=300,top=100');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data);
        myWindow.focus();
};
</script>

方法二:用CSS打印媒体查询隐藏(更简洁)

如果你不想操作DOM,可以直接给打印窗口加一段专用CSS,让最后两列在打印时自动隐藏,代码更简洁:

<script type="text/javascript">
function printPage(){
    var tableData = '<table border="1" style="border-collapse:collapse; background-color: lightblue;font-size: large;">'+document.getElementsByTagName('table')[0].innerHTML+'</table>';
    var t='Tabella configurazione slot giorni e ore. &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;';
    // 添加打印专用样式:隐藏表格最后两列(包括表头)
    const printStyle = '<style media="print"> table tr td:last-child, table tr td:nth-last-child(2), table tr th:last-child, table tr th:nth-last-child(2) { display: none; } </style>';
    var data = printStyle + '<button onclick="window.print()">Print this page</button>'+tableData;   
    
    myWindow=window.open('','','width=800,height=600,left=300,top=100');
        myWindow.innerWidth = screen.width;
        myWindow.innerHeight = screen.height;
        myWindow.screenX = 0;
        myWindow.screenY = 0;
        myWindow.document.write(data);
        myWindow.focus();
};
</script>

两种方法都能实现你的需求,你可以选一个测试一下~

备注:内容来源于stack exchange,提问作者isa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:34:49