簡體   English   中英

如何使用JavaScript在div上打印內容?

[英]How to use JavaScript to print the contents on a div?

我想使用print()函數來打印<div class="pagecontent"></div>

我知道你可以做像onClick="window.print()"這樣的東西,但這會打印整個窗口...我只想要打印.pagecontent的內容。

使用JavaScript或jQuery進行此操作最簡單的方法是什么?

最簡單的方法是定義適用於@media=print的樣式表。 它基本上會有類似的東西:

* { 
   display: none;  /* hide all elements when printing */
}

.pageContent {
   display: block; /* make any class="pageContent" elements visible while printing */
}

當然,這會使pageContent元素可見,但其中的任何內容仍然可以從*規則中隱藏。 您必須使用此功能並僅列出應隱藏的頂級元素。

您可以將元素的內容添加到iframe,然后打印iframe。

HTML -

<span>Print Just Me.</span> I'll be omitted.<br />
<iframe id="iframe"></iframe>​

JS -

$('span').on('click', function () {
    $('#iframe').contents().find('body').html($(this).html());
    window.frames['iframe'].print();
});​

這是一個演示: http//jsfiddle.net/zaF3K/

您還可以隱藏iframe,以便在幕后進行:

#iframe {
    display : none;
}​

這是一個演示: http//jsfiddle.net/zaF3K/1/

有jqprint jquery插件,看一看

http://archive.plugins.jquery.com/project/jqPrint

如果你想使用javascript而不是試試這個

 window.printItn = function() {

                var printContent = document.getElementById('pagecontent');

                var windowUrl = 'about:blank';
                var uniqueName = new Date();
                var windowName = 'Print' + uniqueName.getTime();

    //  you should add all css refrence for your html. something like.

                var WinPrint= window.open(windowUrl,windowName,'left=300,top=300,right=500,bottom=500,width=1000,height=500');
                WinPrint.document.write('<'+'html'+'><head><link href="cssreference" rel="stylesheet" type="text/css" /></head><'+'body style="background:none !important"'+'>');
                WinPrint.document.write(printContent.innerHTML);

                WinPrint.document.write('<'+'/body'+'><'+'/html'+'>');
                WinPrint.document.close();
                WinPrint.focus();
                WinPrint.print();
                WinPrint.close();
                }

參見演示http//jsfiddle.net/mu8BG/1/

您可以使用innerHTML獲取div的內容並將其存儲為字符串,然后單獨打印或記錄該片段。

var string_to_print = $('#pagecontent').html();

http://api.jquery.com/html/

使用純javascript你不能,但你可以使用media print CSS 類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM