打印特定的div内容而不显示javascript

时间:2019-04-18 05:05:25

标签: javascript html laravel-5 bootstrap-4

我想通过javascript打印特定的div。没有任何html标签打印时,它工作正常。但是当使用任何HTML 标签,例如p,h1或h2,它被打印为空白页。

这是我的代码

    @extends('layout.master')
    @section('content')
    <div class="separator-breadcrumb border-top">
    </div>
    <div class="row">
         <div class="col-md-12">
              <div class="card">
                  <div class="card-header bg-secondary" style="padding: 7px 1.25rem">
                      <div class="row">
                          <div class="col-md-1">
                               <button onclick="printDiv('printMe')" class="btn btn-danger font-weight-700"> Print
                               </button>
                          </div>
                      </div>
                  </div>
                 <div id="printMe" >
                       <div class="card-body">
                          <h1>
                            Print this only
                          </h1>
                      </div>
                 </div>
              </div>
          </div>
       </div>
   @endsection
    @section('JScript')
      <script>
         function printDiv(divID) {
            var divElements = document.getElementById(divID).innerHTML;
        var oldPage = document.body.innerHTML;
        document.body.innerHTML = divElements;
        window.print();
        document.body.innerHTML = oldPage;
        }
      </script>
  @endsection

1 个答案:

答案 0 :(得分:0)

尝试格式化您的代码,使其不会解析为HTML(用unicode&lt;替换'<'结束标记字符,并将其放在

 tag, to preserve white space:

// try changing from this : var divElements = document.getElementById(divID).innerHTML; var oldPage = document.body.innerHTML; document.body.innerHTML = divElements; // to this : var divElements = document.getElementById(divID).innerHTML; var oldPage = document.body.innerHTML; document.body.innerHTML = '<pre>' + divElements.replace(/</g, '&lt;') + '</pre>';