我如何打开一个新窗口,并通过Javascript将只选择的html元素传递给它(为了以后打印它们的目的)?

How can I open a new window and pass to it (for the later purpose of printing them) only selected html elements with Javascript?

本文关键字:元素 html 打印 选择 一个 新窗口 何打开 窗口 Javascript      更新时间:2023-09-26

如果我的代码像这样:

<table>
<td class="noprint">1</td>
<td class="noprint">2</td>
<td class="print">3</td>
<td class="noprint">4</td>
<td class="noprint">5</td>
<td class="print">6</td>
<td class="noprint">7</td>
<td class="noprint">8</td>
<td class="print">9</td>
</table>

我想用javascript打开一个新窗口,只打印具有class="print"的元素,我该怎么做?Tnx .

你在评论中说你想:

"打开一个新窗口,并"传递"类为"print"的元素到该页"

你可以克隆你的表,删除任何不是class="print"的单元格,得到它的HTML,并把它写出来的新窗口:

var clone = document.querySelector("selector for your table").cloneNode(true);
var list = clone.querySelectorAll("td:not(.print)");
var i;
for (i = 0; i < list.length; ++i) { // QSA returns static lists, so we can loop normally
    list[i].parentNode.removeChild(list[i]);
}
var wnd = window.open();
wnd.document.write("<!doctype html><html><title>Something Appropriate</title></head><body></body></html>");
wnd.document.close();
wnd.document.body.innerHTML = clone.outerHTML

生活例子

但是请注意,大多数时候,这是不必要的。如果你的主窗口有@media screen@media print规则,你可以在主窗口中管理显示的内容和打印的内容,而不必打开一个新的。

示例- CSS:

table {
  border-collapse: collapse;
  border: 1px solid #aaa;
}
td {
  padding: 2px;
  border: 1px solid #aaa;
}
@media screen {
  .print-only {
    display: none;
  }
}
@media print {
  .screen-only {
    display: none;
  }
}
HTML:

<table>
  <tbody>
    <tr>
    <td class="screen-only">Screen Only</td>
    <td class="print-only">Print Only</td>
    <td>Either print or screen</td>
    </tr>
  </tbody>
</table>

生活复制

请注意,当您在屏幕上查看页面时,您看到的是"只打印"answers"打印或屏幕"单元格,但是当您打印(或查看打印预览)时,您看到的是"只打印"answers"打印或屏幕"单元格。

它非常强大,不需要任何脚本

你需要做一个css并给media =" print",像这样:

<link rel="your path" media="print">
/* define these properties into css file: */
.noprint{display: none;}
.print{display: block;}