使用CSS打印div html代码

时间:2018-08-17 08:59:20

标签: html css

我有这个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>

我想要的是打印div标签,该标签包含css格式或至少位置的图像。反正有这样做吗?

1 个答案:

答案 0 :(得分:2)

javascript正在打印innerHTML中的div(仅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>