JS实现页面局部打印效果

点击预览弹出卡片,打印卡片中的内容。

<html>
	<head>
	</head>
	<body>
		<div>
			<h1>文档</h1>
		</div>
		<div>
			<h1>发票</h1>
			<button onclick="doView()">预览</button>
		</div>
		<div id="container">
			<div id="printArea">
				<h1>一.标题</h1>
				<p>1.正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文</p>
				<p>2.正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文</p>
				<p>3.正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文</p>
				<p>4.正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文</p>
				<p>5.正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文</p>
			</div>
			<button onclick="hideContainer()">关闭</button>
			<button onclick="doPrint('printArea')">打印</button>
		</div>
	</body>
</html>
<script type="text/javascript">
	function doPrint(elementId){
		const printContainer = document.getElementById(elementId).innerHTML; 
		let iframe = document.getElementById('print-iframe');
		if (!iframe) {
			iframe = document.createElement('iframe');
			iframe.setAttribute('id', 'print-iframe');
			iframe.setAttribute('style', 'position: absolute; width: 0px; height: 0px;left:-500px;top:-500px;');
			document.body.appendChild(iframe);

			var doc = iframe.contentWindow.document;
			doc.write('<title>局部打印</title>');
			doc.write('<style media="print">@page {size: auto; margin: 0 mm;}</style>'); //可以调整打印时特有的样式
			doc.write('<div style="margin: 20px auto;">');
			doc.write(printContainer);
			doc.write('</div>');
			doc.close();	
		}
		// iframe.contentWindow.focus();
		iframe.contentWindow.print();
	}

	function doView() {
      var container = document.getElementById("container");
      container.classList.toggle("show");
    }

    function hideContainer() {
      var container = document.getElementById("container");
      container.classList.remove("show");
    }
</script>
<style>
	#container{
		display: none;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 800px;
		height: 600px;
		background-color: #f1f1f1;
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 20px;
		text-align: center;
	}
    .show {
      display: block !important;
    }
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值