如何打印指定的div(无需手动禁用页面上的所有其他内容)?
我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。
该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。
如何打印指定的div(无需手动禁用页面上的所有其他内容)?
我想要避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。
该页面包含了几个表格,其中一个包含了我想打印的div -表格是用web的视觉样式设计的,不应该显示在打印中。
当前回答
桑德罗的方法很有效。
我对它进行了调整,以允许多个printMe链接,特别是在选项卡页面和扩展文本中使用。
function processPrint(printMe){<——在这里调用一个变量
var printReadyElem = document.getElementById(printMe);<——删除了printMe周围的引号以请求一个变量
< a href = " javascript:无效(processPrint (' divID '));>Print</a> <——将要打印的div ID传递到函数上,将printMe变量转换为div ID。需要单引号
其他回答
试试这个:
function printElement($elem){
var $customPrintSection = document.getElementById('customPrintSection'),
$customPrintSectionCss = document.getElementById('customPrintSectionCss');
if ($customPrintSection){
$customPrintSection.remove();
}
if ($customPrintSectionCss){
$customPrintSectionCss.remove();
}
$customPrintSection = document.createElement('div');
$customPrintSection.id = 'customPrintSection';
$customPrintSectionCss = document.createElement('style');
$customPrintSectionCss.id = 'customPrintSectionCss';
document.body.appendChild($customPrintSection);
document.body.appendChild($customPrintSectionCss);
$customPrintSection.innerHTML = $elem.innerHTML;
$customPrintSectionCss.innerHTML = '@media screen { div#customPrintSection { display: none; } } @media print { body *:not(div#customPrintSection):not(div#customPrintSection *) { display: none; } div#customPrintSection a[href]:after { content: none !important; } }';
window.print();
$customPrintSection.remove();
$customPrintSectionCss.remove();
}
我喜欢这个解决方案,因为它不像css解决方案那样影响整个页面,它在一个特定的答案中使所有主体元素立即不可见。所以如果需要的话,祝你能打印整页。
我也更喜欢“display: none”方法而不是“visibility: hidden”方法,所以没有必要将可打印元素设置为绝对元素并将其对齐到左上角。但我想这是主观的。
最后,它真的打败了新的窗口方法。
到目前为止,所有的答案都是有缺陷的——它们要么涉及在所有内容中添加class="noprint",要么会在#printable中混乱显示。
我认为最好的解决方案是在不可打印的东西周围创建一个包装器:
<head>
<style type="text/css">
#printable { display: none; }
@media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<body>
<div id="non-printable">
Your normal page contents
</div>
<div id="printable">
Printer version
</div>
</body>
当然,这并不是完美的,因为它涉及到在HTML中移动一些东西……
嗯……使用样式表的类型进行打印…例如:
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
print.css:
div { display: none; }
#yourdiv { display: block; }
您是否可以使用打印样式表,并使用CSS来排列想要打印的内容?阅读这篇文章获取更多的建议。
printDiv()函数出现了几次,但在这种情况下,将丢失所有绑定元素和输入值。所以,我的解决方案是为所有名为“body_allin”的东西创建一个div,并在第一个名为“body_print”的外部创建另一个div。
然后调用这个函数:
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
document.getElementById("body_print").innerHTML = printContents;
document.getElementById("body_allin").style.display = "none";
document.getElementById("body_print").style.display = "";
window.print();
document.getElementById("body_print").innerHTML = "";
document.getElementById("body_allin").style.display = "";
document.getElementById("body_print").style.display = "none";
}