打印标题中的日期和时间



默认情况下,window.print仅显示在页眉中的打印日期。我需要在页眉中显示打印日期和时间。我该怎么做?

如果有办法定义它的运行时间?例如:

<style type="text/css" media="print"> ...

还是在其他地方?

这是一个简单的解决方案,可能不是最好的,但可以完成以下工作:

将其添加到<body>开口下方:

<div id="printDateTime"></div>

要获取日期和时间,请使用javascript:

const today = new Date();
const date = today.getDate() + "/" + today.getMonth() + "/" + today.getFullYear();
const time =
today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
document.getElementById("printDateTime").innerHTML =
"Printed on: " + date + " at " + time;

在css中设置为display: none;

#printDateTime {
display: none;
}

并且在print media queries:中设置为display: block;

@media print {
#printDateTime {
display: block;
}
}

如果你想,你可以根据你的需要进行样式设置,比如:

#printDateTime {
display: none;
color: red;
font-size: 12px;
}

在媒体查询中也不需要添加样式CSS。


代码笔:https://codepen.io/manaskhandelwal1/pen/LYRgXdx

在此处测试(只需进入页面并按Ctrl/Cmd+p(:https://codepen.io/manaskhandelwal1/full/LYRgXdx

最新更新