我正在尝试用HTML实现打印功能.我知道我可以打印整个页面window.print(),但是如何只打印特定的页面元素?例如一个特定的<DIV>Some text to print</DIV>.
ash*_*exm 33
您可以使用特定于打印的CSS样式表并隐藏除要打印的内容之外的所有内容.
<div class="no-print">I won't print</div><div class="something-else">I will!</div>
只是no-print该类将被隐藏,但任何带有打印类的东西都会显示出来.
<style type="text/css" media="print">
.no-print { display: none; }
</style>
Run Code Online (Sandbox Code Playgroud)
Rav*_*afi 14
如果您熟悉jQuery,可以使用如下的jQuery Print Element插件:
$('SelectorToPrint').printElement();
Run Code Online (Sandbox Code Playgroud)
我找到了一个不存在其他解决方案所存在问题的解决方案。它将打印元素复制到正文中,并且相当优雅和通用:
CSS:
@media print {
body *:not(.printable, .printable *) {
// hide everything but printable elements and their children
display: none;
}
}
Run Code Online (Sandbox Code Playgroud)
JS:
function printElement(e) {
let cloned = e.cloneNode(true);
document.body.appendChild(cloned);
cloned.classList.add("printable");
window.print();
document.body.removeChild(cloned);
}
Run Code Online (Sandbox Code Playgroud)
唯一的限制是该元素会丢失从其先前父元素继承的样式。但它适用于文档结构中的任意元素
创建通用的东西以用于任何HTML元素
HTMLElement.prototype.printMe = printMe;
function printMe(query){
var myframe = document.createElement('IFRAME');
myframe.domain = document.domain;
myframe.style.position = "absolute";
myframe.style.top = "-10000px";
document.body.appendChild(myframe);
myframe.contentDocument.write(this.innerHTML) ;
setTimeout(function(){
myframe.focus();
myframe.contentWindow.print();
myframe.parentNode.removeChild(myframe) ;// remove frame
},3000); // wait for images to load inside iframe
window.focus();
}
Run Code Online (Sandbox Code Playgroud)
用法:
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
Run Code Online (Sandbox Code Playgroud)
希望这有助于
问候
拉夫•库拉纳
简单的 html 和纯 javascript 效果最好。参数“this”指的是当前的id,因此该函数对于所有id都是通用的。通过使用“ref.textContent”而不是“ref.innerHTML”,您可以仅提取文本内容进行打印。
html 正文:
<div id="monitor" onclick="idElementPrint(this)">element to print
<img src="example.jpg" width="200">
</div>
Run Code Online (Sandbox Code Playgroud)
纯 JavaScript:
/*or:
monitor.textContent = "click me to print content";
const imga = new Image(200); //width
imga.src = "./example.jpg";
monitor.appendChild(imga);
*/
const idElementPrint = ref => {
const iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
const pri = iframe.contentWindow;
pri.document.open();
pri.document.write(ref.innerHTML);
pri.document.close();
pri.focus();
pri.print();
pri.onafterprint = () => { document.body.removeChild(iframe); }
}
Run Code Online (Sandbox Code Playgroud)