在chrome中打印时,javascript-css隐藏页面网址(但仍显示页码)

时间:2018-07-10 10:57:29

标签: javascript html css google-chrome printing

当用户尝试打印网页时,我想隐藏浏览器添加到打印页面的所有其他细节,但仍只显示页码。

像这样: enter image description here

我设法用以下CSS代码隐藏了所有这些代码:

@page{
    size: A4;
    margin: 8mm;
}

或仅使用CSS代码排名前2:

@page{
        size: A4;
        margin: 8mm 8mm 9mm;
}

但是,在打印页面时隐藏url结构仍然没有实现我的目标。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

根据设计,您无法触摸浏览器的打印对话框。

使用@page{ margin: 8mm}时,默认页边距会变小,所有多余的细节都会消失,因为它们无处可容。

因为页码和页面URL都在页面底部-您不能只显示或隐藏其中之一,但是,可以在显示打印对话框之前更改页面URL,然后进行更改打印结束后返回,因此打印的页面不会显示URL结构。

//custom function to fire when print dialog is closed
function afterPrintOver (){
    console.log('Print is over.');
    //remove our empty state
    window.history.back();
}

//detect when the user is click `Ctrl + P` to print
document.addEventListener('keydown', function(e){
    const PKeyCode = 80;
    if( e.ctrlKey && e.keyCode === PKeyCode ){
        //stop the browser from open the print dialog
        event.preventDefault();

        //add an empty state, the url now will be www.yourDomainName.com/#/print
        window.history.pushState('', '', '#/print');

        //call our afterPrintOver function, and 'pass' the result of `window.print()`*
        afterPrintOver(window.print());
});

这是怎么回事:

  1. 用户按 CTRL + P
  2. 我们使用自定义相对网址在历史记录中添加一个空状态
  3. 浏览器的打印对话框显示自定义网址
  4. 打印结束(或用户关闭打印对话框)
  5. 我们删除了空状态,这会将网址更改回正确的网址

*诀窍在于,我们的afterPrintOver函数在window.print()函数结束并返回undefined之前不会启动,这意味着打印过程结束了。