浏览器对打印特定媒体查询的支持多种多样,似乎没有任何好的资源。跨浏览器确实不可能,在某些浏览器中根本不支持。例如,Safari 似乎使用浏览器的大小而不是页面来进行媒体查询。
您可以让它在 Chrome 和 Firefox 中运行。我使用大小比敲了一个非常粗略的演示,以展示通过一些工作可以实现什么。目前在 macOS 上测试并使用当前版本的 Chrome 和 Firefox。您应该在页面的开头收到一条带有打印页面大小的消息(仅在打印时)。
http://gsgd.co.uk/sandbox/print-test.html
主要技巧是使用 vw 单位来检查高度,因此使用纵横比可以针对特定的纸张尺寸:
@media print and (min-height:160vw) and (max-height: 170vw) { /* legal-size styling */ .standard.container::before { content: "LEGAL"; } }
@media print and (min-height:135vw) and (max-height: 145vw) { /* A4 styling */ .standard.container::before { content: "A4"; } }
@media print and (min-height:125vw) and (max-height: 135vw) { /* letter-size styling */ .standard.container::before { content: "LETTER"; } }
不幸的是,Chrome 的打印页面大小似乎与输出页面大小不匹配,所以我猜测某些样式与 Chrome 匹配。
@media print and (min-height:120vw) and (max-height: 150vw) { /* legal-size styling */ .chrome.container::before { content: "LEGAL"; } }
@media print and (min-height:100vw) and (max-height: 120vw) { /* A4 styling */ .chrome.container::before { content: "A4"; } }
@media print and (min-height:80vw) and (max-height: 100vw) { /* letter-size styling */ .chrome.container::before { content: "LETTER"; } }
使用极其简陋的浏览器检测器脚本
if(navigator.userAgent.match(/chrome/i)) {
document.querySelector('.container').className = 'chrome container'
}
让 Safari 工作的想法是手动调整窗口大小,但这可能需要大量工作,并且需要用户预先选择打印尺寸。
所有这一切都表明您可能会获得更好的里程来修复您的布局以更好地响应不同的宽度。