在 JavaScript 中列印 div 元素的內容
 
本教程啟發了兩種不同的方法,用於在 JavaScript 中列印 div 元素的內容。為此,我們可以使用 JavaScript window 列印命令來列印當前視窗的內容。
列印對話方塊由 print() 方法開啟,允許使用者選擇所需的列印選項。
例如,我們可以在那裡使用不同的目的地,儲存為 .pdf 檔案、傳真、Windows 10 的 OneNote 等等。另一方面,element.outerHTML 屬性在網頁上列印 div 元素的內容。
在 JavaScript 中使用 window 列印命令列印 div 元素的內容
HTML 程式碼:
<!DOCTYPE html>
<html>
	<head>
		<title>
       		Print the Content of A Div Element in JavaScript
 		</title>
 	</head>
	<body>
 		<div id="printContent">
 			<h2>This is the Heading Inside the div</h2>
 			<p>
              This is a paragraph inside the div and will be printed
              on the a separate pdf file as soon as you click the button.
 			</p>
 		</div>
 		<input type="button" value="Click Here" onclick="printDivContent()">
	</body>
</html>
JavaScript 程式碼:
function printDivContent() {
  var divElementContents = document.getElementById('printContent').innerHTML;
  var windows = window.open('', '', 'height=400, width=400');
  windows.document.write('<html>');
  windows.document.write('<body > <h1>Div\'s Content Are Printed Below<br>');
  windows.document.write(divElementContents);
  windows.document.write('</body></html>');
  windows.document.close();
  windows.print();
}
輸出:

在此輸出中,單擊按鈕時會呼叫函式 printDivContent()。
在這個函式中,我們儲存了一個 id 值為 printContent 的 HTML 元素的 innerHTML(內容)。在我們的例子中,它是一個 <div> 元素。
根據引數值和瀏覽器設定,window.open() 開啟一個新標籤頁或一個新瀏覽器視窗。它需要三個引數:URL、視窗名稱和視窗特徵列表(高度、寬度等)。
我們的示例程式碼將前兩個引數留空,並給出一個逗號分隔的列表,其中包含 height=400 和 width=400。write() 函式直接寫入開啟的 HTML 文件流。
我們正在使用 windows.document.write() 在新的瀏覽器視窗中書寫。
close() 函式關閉當前視窗或它被引用或呼叫的特定視窗。print() 方法列印當前視窗的內容;它還會開啟一個列印對話方塊,讓使用者選擇首選的列印選項。
你可以在此處找到有關 window 命令的更多資訊。
在 JavaScript 中使用 outerHTML 屬性列印 div 元素的內容
HTML 程式碼:
<!DOCTYPE html>
<html>
	<head>
 		<title>
    		Print the Content of A Div Element in JavaScript
 		</title>
 	</head>
	<body>
		<div id="printContent">
			<h2>This is the Heading Inside the div</h2>
			<p>
              This is a paragraph inside the div and will be printed
        	  on the a web page as soon as you click the button.
           </p>
 		</div>
		<input type="button" value="Click Here" onclick="printDivContent()">
 		<p id="demo"></p>
 	</body>
</html>
JavaScript 程式碼:
function printDivContent() {
  var printDivContents = document.getElementById('printContent');
  document.getElementById('demo').innerHTML = printDivContents.outerHTML;
}
輸出:

點選按鈕時呼叫函式 printDivContent()。此函式獲取第一個 id 為 printContent 的元素,它是一個 <div> 元素。
此外,我們將 id 為 demo 的元素的 innerHTML(內容)替換為 printDivContents.outerHTML。這裡,outerHTML 屬性輸出或設定特定的 HTML 元素及其內容,包括開始和結束標記及其屬性。
