我要打印仅包含所选部分的正文
点击此方法,页面对齐方式就会改变
// app
<div class="header">
<ul>
<li>Home</li>
<li>Page</li>
<li>Contact</li>
</ul>
</div>
<div id="payment-receipt">
<div>
<p>Price$24.78</p>
<p>Product Status About to reach </p>
</div>
</div>
// js
printDiv() {
//Get the HTML of div
var divElements = document.getElementById('payment-receipt').innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
在单击方法之前和单击方法之后,对齐方式应保持不变
答案 0 :(得分:0)
您可以使用print stylesheet
@media print{
/* hide this element on media print */
.header{
display:none;
}
}
<div class="header">
<ul>
<li>Home</li>
<li>Page</li>
<li>Contact</li>
</ul>
</div>
<div id="payment-receipt">
<div>
<p>Price$24.78</p>
<p>Product Status About to reach </p>
</div>
</div>
答案 1 :(得分:0)
<div class="header">
<ul>
<li>Home</li>
<li>Page</li>
<li>Contact</li>
</ul>
</div>
<div id="payment-receipt" name='clickf'>
<div>
<p>Price$24.78</p>
<p>Product Status About to reach </p>
</div>
</div>
使用javascript no jquery打印选定的部分
var el = document.getElementById('payment-receipt');
if(el){
el.addEventListener('click', print_div, false);
}
function print_div(){
var content = document.getElementById('payment-receipt').innerHTML;
var mywindow = window.open();
mywindow.document.write('<html><head><title>Print</title></head><body >'+content+'</body></html>');
mywindow.print();
document.body.innerHTML =content;
mywindow.close();
return true;
}
答案 2 :(得分:0)
根据Younes Zaidi的答案进行了小幅改动:
var el = document.getElementById('payment-receipt');
if(el){
el.addEventListener('click', print_div, false);
}
function print_div(){
var content = document.getElementById('payment-receipt').innerHTML;
var mywindow = window.open();
mywindow.document.write('<html><head><title>Print</title></head><body >'+ window.getSelection() +'</body></html>');
mywindow.print();
document.body.innerHTML =content;
return true;
}
<div class="header">
<ul>
<li>Home</li>
<li>Page</li>
<li>Contact</li>
</ul>
</div>
<div id="payment-receipt" name='clickf'>
<div>
<p>Price$24.78</p>
<p>Product Status About to reach </p>
</div>
</div>
<textarea id="text"></textarea>
答案 3 :(得分:0)
我遇到了同样的问题-有一个包含用户数据的表格。我必须打印该表格,但也要防止打印不必要的数据,或者只能打印页面中包含数据的特定部分
我如何解决这个问题
1。对于简单案例 隐藏所有不需要的元素,然后在其余部分调用window.print()
.select2-container--default .select2-results>.select2-results__options {
max-height: inherit;
}
2。对于复杂案例 现在在复杂的dom中可能有问题,以我的情况来说很简单,现在让我们看看如何在复杂的dom结构中解决相同的问题
HTML
printForm(){
document.getElementById('element1').style.display='None'
document.getElementById('element2').style.display='None'
document.getElementById('element2').style.display='None'
window.print()
}
JavaScript
<body>
<div id="content">
<!-- Content that has to be printed -->
</div>
<div id="print-content">
<!-- Will be used for printing purpose -->
</div>
</body>