509

如何打印指定的 div(无需手动禁用页面上的所有其他内容)?

我想避免一个新的预览对话框,所以用这个内容创建一个新窗口是没有用的。

该页面包含几个表格,其中一个包含我要打印的 div - 该表格的样式是 Web 的视觉样式,不应在打印中显示。

4

33 回答 33

929

这是一个通用的解决方案,仅使用 CSS,我已经验证它可以工作。

@media print {
  body * {
    visibility: hidden;
  }
  #section-to-print, #section-to-print * {
    visibility: visible;
  }
  #section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}

替代方法不是那么好。使用display很棘手,因为如果任何元素有,display:none那么它的后代都不会显示。要使用它,您必须更改页面的结构。

使用visibility效果更好,因为您可以打开后代的可见性。不可见的元素仍然会影响布局,所以我移动section-to-print到左上角以便正确打印。

于 2010-04-11T22:39:26.437 回答
279

我有一个更好的解决方案,代码最少。

将您的可打印部分放在一个 div 中,其 id 如下:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

然后添加一个类似 onclick 的事件(如上所示),并像我上面所做的那样传递 div 的 id。

现在让我们创建一个非常简单的 javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

注意这有多简单?没有弹出窗口,没有新窗口,没有疯狂的样式,没有像 jquery 这样的 JS 库。真正复杂的解决方案的问题(答案并不复杂,也不是我所指的)是它永远不会在所有浏览器中翻译!如果您想使样式不同,请按照检查答案中所示的方式,将 media 属性添加到样式表链接(media="print")。

没有绒毛,重量轻,它只是工作。

于 2011-09-23T17:16:58.773 回答
128

到目前为止,所有答案都存在相当大的缺陷——它们要么涉及添加到所有内容,要么会在内部class="noprint"搞砸。display#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 中移动一些东西......

于 2009-01-22T12:28:28.750 回答
116

使用 jQuery 就这么简单:

w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();
于 2009-11-06T12:57:54.593 回答
23

您可以使用打印样式表,并使用 CSS 来安排您想要打印的内容吗?阅读这篇文章以获得更多指导。

于 2009-01-22T12:12:20.840 回答
17

我真的不喜欢这些答案中的任何一个。如果您有一个类(例如 printableArea)并将其作为 body 的直接子级,那么您可以在打印 CSS 中执行以下操作:

body > *:not(.printableArea) {
    display: none;
}

//Not needed if already showing
body > .printableArea {
    display: block;
}

对于那些在其他地方寻找 printableArea 的人,您需要确保显示 printableArea 的父母:

body > *:not(.parentDiv),
.parentDiv > *:not(.printableArea) {
    display: none;
}

//Not needed if already showing
body > .printableArea {
    display: block;
}

使用可见性会导致很多间距问题和空白页。这是因为可见性保持元素空间,只是使其隐藏,而显示将其移除并允许其他元素占用其空间。

这个解决方案有效的原因是你没有抓住所有元素,只是身体的直接子元素并隐藏它们。下面使用显示 css 的其他解决方案,隐藏所有元素,这会影响 printableArea 内容中的所有内容。

我不建议使用 javascript,因为您需要一个用户单击的打印按钮,而标准浏览器打印按钮不会产生相同的效果。如果你真的需要这样做,我会做的是存储正文的 html,删除所有不需要的元素,打印,然后将 html 添加回来。如前所述,如果可以的话,我会避免这种情况,并使用上面的 CSS 选项。

注意:您可以使用内联样式将任何 CSS 添加到打印 CSS 中:

<style type="text/css">
@media print {
   //styles here
}
</style>

或者像我通常使用的是链接标签:

<link rel="stylesheet" type="text/css" media="print" href="print.css" />
于 2013-07-23T15:02:28.123 回答
10
  1. 给出要打印 id 的任何元素printMe

  2. 在你的 head 标签中包含这个脚本:

    <script language="javascript">
        var gAutoPrint = true;
    
        function processPrint(){
    
        if (document.getElementById != null){
        var html = '<HTML>\n<HEAD>\n';
        if (document.getElementsByTagName != null){
        var headTags = document.getElementsByTagName("head");
        if (headTags.length > 0) html += headTags[0].innerHTML;
        }
    
        html += '\n</HE' + 'AD>\n<BODY>\n';
        var printReadyElem = document.getElementById("printMe");
    
        if (printReadyElem != null) html += printReadyElem.innerHTML;
        else{
        alert("Error, no contents.");
        return;
        }
    
        html += '\n</BO' + 'DY>\n</HT' + 'ML>';
        var printWin = window.open("","processPrint");
        printWin.document.open();
        printWin.document.write(html);
        printWin.document.close();
    
        if (gAutoPrint) printWin.print();
        } else alert("Browser not supported.");
    
        }
    </script>
    
  3. 调用函数

    <a href="javascript:void(processPrint());">Print</a>
    
于 2009-05-08T23:37:08.703 回答
10

第 1 步:在 head 标签内编写以下 javascript

<script language="javascript">
function PrintMe(DivID) {
var disp_setting="toolbar=yes,location=no,";
disp_setting+="directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
   var content_vlue = document.getElementById(DivID).innerHTML;
   var docprint=window.open("","",disp_setting);
   docprint.document.open();
   docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');
   docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
   docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
   docprint.document.write('<head><title>My Title</title>');
   docprint.document.write('<style type="text/css">body{ margin:0px;');
   docprint.document.write('font-family:verdana,Arial;color:#000;');
   docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}');
   docprint.document.write('a{color:#000;text-decoration:none;} </style>');
   docprint.document.write('</head><body onLoad="self.print()"><center>');
   docprint.document.write(content_vlue);
   docprint.document.write('</center></body></html>');
   docprint.document.close();
   docprint.focus();
}
</script>

第 2 步:通过 onclick 事件调用 PrintMe('DivID') 函数。

<input type="button" name="btnprint" value="Print" onclick="PrintMe('divid')"/>
<div id="divid">
here is some text to print inside this div with an id 'divid'
</div>
于 2013-04-09T11:38:46.890 回答
7
<script type="text/javascript">
   function printDiv(divId) {
       var printContents = document.getElementById(divId).innerHTML;
       var originalContents = document.body.innerHTML;
       document.body.innerHTML = "<html><head><title></title></head><body>" + printContents + "</body>";
       window.print();
       document.body.innerHTML = originalContents;
   }
</script>

于 2013-10-10T09:22:35.447 回答
7

打印特定 Div 或任何元素的最佳方式

printDiv("myDiv");

function printDiv(id){
        var printContents = document.getElementById(id).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
}
于 2020-01-09T14:45:05.343 回答
6

嗯...使用样式表的类型进行打印...例如:

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

打印.css:

div { display: none; }
#yourdiv { display: block; }
于 2009-01-22T12:13:15.300 回答
3

printDiv(divId):在任何页面上打印任何 div 的通用解决方案。

我有一个类似的问题,但我希望 (a) 能够打印整个页面,或者 (b) 打印几个特定区域中的任何一个。我的解决方案,多亏了上面的大部分内容,允许您指定要打印的任何 div 对象。

此解决方案的关键是向打印媒体样式表添加适当的规则,以便打印请求的 div(及其内容)。

首先,创建所需的打印 css 来抑制所有内容(但没有特定规则来允许您要打印的元素)。

<style type="text/css" media="print">
   body {visibility:hidden; }
   .noprintarea {visibility:hidden; display:none}
   .noprintcontent { visibility:hidden; }
   .print { visibility:visible; display:block; }
</style>

请注意,我添加了新的类规则:

  • noprintarea允许您禁止打印 div 中的元素 - 内容和块。
  • noprintcontent允许您禁止打印 div 中的元素 - 内容被禁止,但分配的区域为空。
  • print允许您拥有显示在打印版本中但不在屏幕页面上的项目。这些通常具有屏幕样式的“display:none”。

然后插入三个 JavaScript 函数。第一个只是打开和关闭打印媒体样式表。

function disableSheet(thisSheet,setDisabled)
{ document.styleSheets[thisSheet].disabled=setDisabled; }   

第二个做真正的工作,第三个之后清理。第二个 (printDiv) 激活打印媒体样式表,然后附加一个新规则以允许打印所需的 div,发出打印,然后在最终内务处理之前添加延迟(否则可以在打印实际之前重置样式完毕。)

function printDiv(divId)
{
  //  Enable the print CSS: (this temporarily disables being able to print the whole page)
  disableSheet(0,false);
  //  Get the print style sheet and add a new rule for this div
  var sheetObj=document.styleSheets[0];  
  var showDivCSS="visibility:visible;display:block;position:absolute;top:30px;left:30px;";
  if (sheetObj.rules) { sheetObj.addRule("#"+divId,showDivCSS); }
  else                { sheetObj.insertRule("#"+divId+"{"+showDivCSS+"}",sheetObj.cssRules.length); }
  print();
  //  need a brief delay or the whole page will print
  setTimeout("printDivRestore()",100);  
}

最后的函数删除添加的规则并再次将打印样式设置为禁用,以便可以打印整个页面。

function printDivRestore()
{
  // remove the div-specific rule
  var sheetObj=document.styleSheets[0];  
  if (sheetObj.rules) { sheetObj.removeRule(sheetObj.rules.length-1); }
  else                { sheetObj.deleteRule(sheetObj.cssRules.length-1); }
  //  and re-enable whole page printing
  disableSheet(0,true);
}

唯一要做的另一件事是在您的加载处理中添加一行,以便最初禁用打印样式,从而允许整页打印。

<body onLoad='disableSheet(0,true)'>

然后,您可以从文档中的任何位置打印 div。只需从按钮或其他任何地方发出 printDiv("thedivid") 。

这种方法的一大优点是它提供了从页面中打印选定内容的通用解决方案。它还允许对打印的元素使用现有样式 - 包括包含 div。

注意:在我的实现中,这必须是第一个样式表。如果您需要稍后在图纸序列中进行,请将图纸参考 (0) 更改为适当的图纸编号。

于 2011-01-22T21:36:50.717 回答
3

如果没有 CSS 小丑,带有 iframe 的 html 和纯 javascript 工作得最好。然后只需单击要打印的文本。带有文本内容的 id 元素的当前示例;

html正文:

<div id="monitor" onclick="idElementPrint()">text i want to print</div>

纯JavaScript:

//or: monitor.textContent = "click me to print textual content";

const idElementPrint = () => {
    let ifram = document.createElement("iframe");
    ifram.style = "display:none";
    document.body.appendChild(ifram);
    pri = ifram.contentWindow;
    pri.document.open();
    pri.document.write(monitor.textContent);
    pri.document.close();
    pri.focus();
    pri.print();
    }
于 2020-11-10T16:51:12.077 回答
2

使用 CSS 3,您可以使用以下内容:

body *:not(#printarea) {
    display: none;
}
于 2009-01-22T12:14:31.507 回答
2

我使用 JavaScript 获取内容并创建了一个可以打印的窗口...

于 2009-02-03T13:06:46.637 回答
2

Sandro 的方法效果很好。

我对其进行了调整以允许多个 printMe 链接,特别是用于标签页和扩展文本。

function processPrint(printMe){ <-- 在这里调用一个变量

var printReadyElem = document.getElementById(printMe); <-- 删除 printMe 周围的引号以要求变量

<a href="javascript:void(processPrint('divID'));">Print</a><-- 将要打印的 div ID 传递给函数以将 printMe 变量转换为 div ID。需要单引号

于 2009-06-19T19:58:57.177 回答
2

@Kevin Florida如果你有多个具有相同类的div,你可以像这样使用它:

 <div style="display:none">
   <div id="modal-2" class="printableArea">
     <input type="button" class="printdiv-btn" value="print a div!" />
   </div>
 </div>

我正在使用 Colorbox 内部内容类型

$(document).on('click', '.printdiv-btn', function(e) {
    e.preventDefault();

    var $this = $(this);
    var originalContent = $('body').html();
    var printArea = $this.parents('.printableArea').html();

    $('body').html(printArea);
    window.print();
    $('body').html(originalContent);
});
于 2015-09-15T08:03:36.767 回答
2

就我而言,我必须在页面内打印图像。当我使用投票的解决方案时,我有 1 个空白页和另一个显示图像的页面。希望它会帮助某人。

这是我使用的css:

@media print {
  body * {
    visibility: hidden;
  }

  #not-print * {
    display: none;
  }

  #to-print, #to-print * {
    visibility: visible;
  }

  #to-print {
    display: block !important;
    position: absolute;
    left: 0;
    top: 0;
    width: auto;
    height: 99%;
  }
}

我的html是:

<div id="not-print" >
  <header class="row wrapper page-heading">

  </header>

  <div class="wrapper wrapper-content">
    <%= image_tag @qrcode.image_url,  size: "250x250" , alt: "#{@qrcode.name}" %>
  </div>
</div>

<div id="to-print" style="display: none;">
  <%= image_tag @qrcode.image_url,  size: "300x300" , alt: "#{@qrcode.name}" %>
</div>
于 2016-06-17T14:18:10.987 回答
2

在不影响当前页面的情况下再增加一种方法,并且在打印时也会保留 css。这里的选择器必须是特定的 div 选择器,我们需要打印哪些内容。

printWindow(selector, title) {
   var divContents = $(selector).html();
   var $cssLink = $('link');
   var printWindow = window.open('', '', 'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth  * 0.6);
   printWindow.document.write('<html><head><h2><b><title>' + title + '</title></b></h2>');
   for(var i = 0; i<$cssLink.length; i++) {
    printWindow.document.write($cssLink[i].outerHTML);
   }
   printWindow.document.write('</head><body >');
   printWindow.document.write(divContents);
   printWindow.document.write('</body></html>');
   printWindow.document.close();
   printWindow.onload = function () {
            printWindow.focus();
            setTimeout( function () {
                printWindow.print();
                printWindow.close();
            }, 100);  
        }
}

这里提供了一些超时显示外部 css 被应用到它。

于 2018-02-15T05:22:13.857 回答
2

适合空间空高度的最佳 css:

@media print {
  body * {
    visibility: hidden;
    height:0;
  }
  #section-to-print, #section-to-print * {
    visibility: visible;
    height:auto;
  }
  #section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}
于 2018-04-19T08:20:53.550 回答
1

您可以使用单独的 CSS 样式来禁用除 ID 为“printarea”的内容之外的所有其他内容。

参见CSS Design: Going to Print以获得进一步的解释和示例。

于 2009-01-22T12:14:16.827 回答
1

如果你只想打印这个 div,你必须使用指令:

@media print{
    *{display:none;}
    #mydiv{display:block;}
}
于 2009-01-22T17:21:44.337 回答
1

printDiv() 函数出现了几次,但在这种情况下,您失去了所有绑定元素和输入值。因此,我的解决方案是为名为“body_allin”的所有内容创建一个 div,并为第一个名为“body_print”的内容创建另一个。

然后你调用这个函数:

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";

}
于 2014-02-27T17:47:42.227 回答
1

我尝试了许多提供的解决方案。没有一个能完美运行。他们要么失去 CSS 或 JavaScript 绑定。我找到了一个既不会丢失 CSS 也不会丢失 JavaScript 绑定的完美且简单的解决方案。

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p>

Javascript:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }
于 2017-11-09T15:54:29.210 回答
1

我参加这个聚会很晚了,但我想用另一种方法加入。我编写了一个名为PrintElements的小型 JavaScript 模块,用于动态打印网页的各个部分。

它通过迭代选定的节点元素来工作,对于每个节点,它会向上遍历 DOM 树直到 BODY 元素。在每个级别,包括初始级别(即要打印的节点的级别),它都将标记类 ( pe-preserve-print) 附加到当前节点。然后将另一个标记类 ( pe-no-print) 附加到当前节点的所有兄弟节点,但前提是pe-preserve-print它们上没有类。作为第三幕,它还将另一个类附加到保留的祖先元素pe-preserve-ancestor

一个非常简单的补充仅打印 css 将隐藏和显示相应的元素。这种方法的一些好处是保留了所有样式,它不会打开新窗口,不需要移动大量 DOM 元素,并且通常不会侵入您的原始文档。

请参阅演示,或阅读相关文章了解更多详细信息

于 2019-03-10T19:07:36.327 回答
1

我找到了解决方案。

@media print {
    .print-area {
        background-color: white;
        height: 100%;
        width: auto;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index:1500;
        visibility: visible;
    }
    @page{
        size: portrait;
        margin: 1cm;
    }
/*IF print-area parent element is position:absolute*/
    .ui-dialog,
    .ui-dialog .ui-dialog-content{
        position:unset !important;
        visibility: hidden;
    }
}
于 2019-09-25T04:55:22.493 回答
1
It's better solution. You can use it Angualr/React

html

 <div class="row" id="printableId">
      Your html 
    </div>

Javascript

   function printPage(){
        
        var printHtml = window.open('', 'PRINT', 'height=400,width=600');
    
        printHtml.document.write('<html><head>');
        printHtml.document.write(document.getElementById("printableId").innerHTML);
        printHtml.document.write('</body></html>');
    
        printHtml.document.close(); 
        printHtml.focus(); = 10*/
    
        printHtml.print();
        printHtml.close();
    
        return true;
    
      }
于 2021-07-27T12:01:05.663 回答
1

我尝试了许多提供的解决方案。没有一个能完美运行。它们要么丢失 CSS,要么不适用于所有浏览器。我找到了一个完美而简单的解决方案,既不会丢失 CSS,也可以完美地适用于所有浏览器。

html

<div class="row" id="print-div">
      Your html 
    </div>

打字稿

let popupWin = window.open('', '_blank', 'width=1080,height=595');
let printContents = document.getElementById("print-div").innerHTML;
let printHead = document.head.innerHTML;
popupWin.document
    .write(`<html>
     ${printHead}
    <body onload="window.print();">${printContents}</body></html>`);
popupWin.document.close();
于 2022-02-15T11:05:59.777 回答
0

使用特殊的样式表进行打印

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

然后为每个标签添加一个类,即“noprint”,这是您不想打印的内容。

在 CSS 中使用

.noprint {
  display: none;
}
于 2009-01-22T12:14:11.943 回答
0

你可以使用这个:http: //vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/

或者将visibility:visiblevisibility:hiddencss 属性一起使用@media print{}

'display:none' 将隐藏所有嵌套的 'display:block'。那不是解决方案。

于 2013-04-05T13:21:42.400 回答
0

我有多个图像,每个图像都有一个按钮,需要单击一个按钮来打印每个带有图像的 div。如果我在浏览器中禁用了缓存,并且图像大小在 Chrome 中没有改变,则此解决方案有效:

        function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');

        w.document.close(); // necessary for IE >= 10
        w.focus(); // necessary for IE >= 10

        return true;
    }

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
于 2016-10-21T14:45:43.113 回答
0

所有答案都有权衡,不能用于所有情况。它们分为 3 类:

  1. 使用打印样式表。这需要构建整个网站以具有打印意识。

  2. 隐藏所有元素<body>并仅显示可打印元素。这适用于简单的页面,但对于复杂的页面却很棘手。

  3. 使用可打印元素的内容打开一个新窗口或将<body>内容替换为该元素的内容。第一个会失去所有样式,第二个是杂乱无章的,可以破坏事件。

没有一种解决方案可以适用于所有情况,因此拥有所有这些选择很好,我正在添加另一种在某些情况下效果更好的解决方案。这个解决方案是两个类别的混合:隐藏 的所有内容<body>,然后将可打印元素的内容复制到一个新的<div>并将其附加到<body>. 打印后去掉新添加<div>的,显示内容<body>背部。这样,您就不会丢失样式或事件,也不会因为打开新窗口而搞砸。但与所有其他解决方案一样,它不适用于所有情况。如果您的可打印元素的样式取决于其父元素,您将丢失这些样式。独立于其父元素来设置可打印元素的样式仍然比为打印整个网站设置样式要容易得多。

唯一的障碍是弄清楚如何选择<body>. 对于简单的页面,通用样式body>*就可以了。但是,复杂的页面通常在 `s<script>的末尾有标签,body' and also some 用于对话框等。隐藏所有这些很好,但你不想在打印后显示它们。

就我而言,我构建了所有可能的网站,其中包含三个部分<body><header>、、<footer>和它们之间<div id="Content">。根据您的情况调整以下函数的第一行:

function PrintArea(selector) {
    //First hide all content in body.
    var all = $("body > header, body > #Content, body > footer")
    all.hide();
    //Append a div for printing.
    $("body").append('<div id="PrintMe">');
    //Copy content of printing area to the printing div.
    var p = $("#PrintMe");
    p.html($(selector).html());
    //Call the print dialog.
    window.print();
    //Remove the printing div.
    p.remove();
    //Show all content in body.
    all.show();
}

我使用 jQuery 是因为它更干净、更简单,但如果您愿意,您可以轻松地将其转换为 vanilla JavaScript。当然,您可以按照建议的方式更改varlet局部变量。

于 2021-06-09T17:37:16.487 回答
-1

基于@Kevin Florida 的回答,我设法避免由于覆盖内容而禁用当前页面上的脚本。我使用其他名为“printScreen.php”(或 .html)的文件。将要打印的所有内容包装在 div“printSource”中。使用 javascript,打开一个您之前创建的新窗口(“printScreen.php”),然后在顶部窗口的“printSource”中获取内容。

这是代码。

主窗口:

echo "<div id='printSource'>";
//everything you want to print here
echo "</div>";

//add button or link to print
echo "<button id='btnPrint'>Print</button>";

<script>
  $("#btnPrint").click(function(){
    printDiv("printSource");
  });

  function printDiv(divName) {
   var printContents = document.getElementById(divName).innerHTML;
   var originalContents = document.body.innerHTML;
   w=window.open("printScreen.php", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=50,left=50,width=900,height=400");
   }
</script>

这是“printScreen.php” - 获取要打印的内容的其他文件

<head>
// write everything about style/script here (.css, .js)

</head>
<body id='mainBody'></body>
</html>


<script>
    //get everything you want to print from top window
    src = window.opener.document.getElementById("printSource").innerHTML;

    //paste to "mainBody"
    $("#mainBody").html(src);
    window.print();
    window.close();
</script>
于 2020-01-16T01:39:50.847 回答