更新时间:2022-12-08 10:42:44
这是一个通用的解决方案,只使用 CSS ,我已经验证可以使用。
Here is a general solution, using CSS only, which I have verified to work.
@media print {
body * {
visibility: hidden;
}
#section-to-print, #section-to-print * {
visibility: visible;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
替代方法并不是那么好。使用 display
是很棘手的,因为如果任何元素有 display:none
那么它的后代都不会显示。要使用它,您必须更改页面的结构。
Alternative approaches aren't so good. Using display
is tricky because if any element has display:none
then none of its descendants will display either. To use it, you have to change the structure of your page.
使用可见性
效果更好,因为您可以转关于后代的可见度。隐形元素仍会影响布局,所以我将 section-to-print
移到左上方,以便正确打印。
Using visibility
works better since you can turn on visibility for descendants. The invisible elements still affect the layout though, so I move section-to-print
to the top left so it prints properly.