我有这个html代码
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
<div class="container">
<div class="row">
<div class="col s6 l6">
<div class="center" id="div_id" style="height: 400px;width: 600px; position:relative; background-color: #ff0;">
<img class="responsive-img" id="profile" width="200" src="https://picsum.photos/200">
</div>
</div>
<div class="col s6 l6">
<div class="card-panel" id="first_name">
<span class="black-text"></span>
</div>
<a class="waves-effect waves-light btn" id="print" onclick="printDiv('div_id')">PRINT</a>
</div>
</div>
</div>
我想要的是打印包含具有CSS格式或至少位置的图像的div标签。 无论如何都可以这样做吗?
javascript 正在打印div
的innerHTML
(仅限img
(。通过将printContents
变量更改为outerHTML
,您还可以获得其样式div
:
var printContents = document.getElementById(divName).outerHTML;
function printDiv(divName) {
var printContents = document.getElementById(divName).outerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
body { -webkit-print-color-adjust: exact !important; }
<div class="container">
<div class="row">
<div class="col s6 l6">
<div class="center" id="div_id" style="height: 400px;width: 600px; position:relative; background-color: #ff0;">
<img class="responsive-img" id="profile" width="200" src="https://picsum.photos/200">
</div>
</div>
<div class="col s6 l6">
<div class="card-panel" id="first_name">
<span class="black-text"></span>
</div>
<a class="waves-effect waves-light btn" id="print" onclick="printDiv('div_id')">PRINT</a>
</div>
</div>
</div>