为什么css@media print在某些div上不起作用



我对这个html代码有问题,

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#div1 {position:fixed;}
#div2 {display:none;}
#div3 {display:none;}

@media print {
#div1 {display:none;}
#div2 {display:none;}
#div3 {display:block;}
}
</style>
</head>
<body>
<div id="div1">
<div>Contents of #div1</div><br/>
<button id="btn1">Go to #div2</button>
</div>
<div id="div2">
<div>Contents of #div2</div><br/>
<button id="btn2">Go to #div1</button><br/><br/>
<button id="btn3">Print</button>
</div>
<div id="div3">Contents of #div3</div>
<script>
$(document).ready(function() {
$("#btn1").on("click",function() {
$("#div1").fadeOut("fast");
$("#div2").fadeIn("fast");
});
$("#btn2").on("click",function() {
$("#div2").fadeOut("fast");
$("#div1").fadeIn("fast");
});
$("#btn3").on("click",function() {
window.print();
});
});
</script>
</body>
</html>

让我告诉你我希望这段代码发生什么,所以,当页面加载时,它只显示#div1,当我点击#btn1时,它隐藏#div1并显示#div2,当我单击#btn2时,它藏起#div2并显示#div 1,当我们点击#btn3时,它打印页面,它应该只在打印预览页面中显示#div3,但是,这里的问题是,在打印预览页中,它显示#div 2和#div3,我不知道为什么,我只想在打印预览页中显示#div3,有人能帮我吗?

jquery fadein和fadeout调用更改了display属性的优先级,因此它们也出现了,在css中添加要覆盖的重要内容。参考:CSS@media print根本不起作用
更改您的样式,如下所示:

@media print{
#div1{display:none!important;}
#div2{dispay:none!重要;}

这也应该起作用:

@media print {
#div1 {visibility:hidden; height:0; width:0}
#div2 {visibility:hidden; height:0; width:0}
#div3 {display:block;}
}

$(document).ready(function() {
$("#btn1").on("click",function() {
$("#div1").fadeOut("fast");
$("#div2").fadeIn("fast");
});
$("#btn2").on("click",function() {
$("#div2").fadeOut("fast");
$("#div1").fadeIn("fast");
});
$("#btn3").on("click",function() {
window.print();
});
});
#div1 {position:fixed;}
#div2 {display:none;}
#div3 {display:none;}

@media print {
#div1 {visibility:hidden; height:0; width:0}
#div2 {visibility:hidden; height:0; width:0}
#div3 {display:block;}
}
<div id="div1">
<div>Contents of #div1</div><br/>
<button id="btn1">Go to #div2</button>
</div>
<div id="div2">
<div>Contents of #div2</div><br/>
<button id="btn2">Go to #div1</button><br/><br/>
<button id="btn3">Print</button>
</div>
<div id="div3">Contents of #div3</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

最新更新