是否可以通过 JS 只打印 DOM 的一部分?
如果唯一的方法是指定打印样式表,我认为可以在浏览器打印功能调用之前动态应用打印样式表?
最佳答案
试一下:
self.printDomElement = function(selector) {
var newWindow = window.open("", "Test", "width=500,height=500,scrollbars=1,resizable=1");
var sectionOfDom = $(selector);
newWindow.document.open();
for (var i = 0; i < sectionOfDom.length; i++) {
newWindow.document.write(sectionOfDom[i].innerHTML);
}
newWindow.document.close();
newWindow.print();
newWindow.close();
};
编辑:根据我的阅读,iFrame 仅在不违反 same origin policy 的情况下才能工作。 。还有一种不同的方式来访问 iFrame 的 innerHTML
属性,因此如果它是 iFrame,则必须有一个条件才能以不同的方式访问它。
以下是处理 iframe 内容的已编辑代码:
self.printDomElement = function(selector) {
var newWindow = window.open("", "Test", "width=500,height=500,scrollbars=1,resizable=1");
var sectionOfDom = $(selector);
newWindow.document.open();
for (var i = 0; i < sectionOfDom.length; i++) {
if ($(sectionOfDom[i]).is('iframe')) {
try {
newWindow.document.write(sectionOfDom[i].contentDocument.body.innerHTML);
} catch(err) {
console.log('Caught exception with message: [' + err.message + '] while trying to write content to print window.');
}
} else {
newWindow.document.write(sectionOfDom[i].innerHTML);
}
}
newWindow.document.close();
newWindow.print();
newWindow.close();
};
关于javascript - 通过 JavaScript 打印网页的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28069259/