通过 JavaScript 打印网页的子集

Printing a subset of a web page via JavaScript

本文关键字:子集 网页 打印 JavaScript 通过      更新时间:2023-09-26

可以通过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只有在不违反同源策略的情况下才能工作。还有一种不同的方法可以访问 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();
    };