使用 css 打印 div 内容的 jQuery Print 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17753420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Print function to print div content with css
提问by Gurjot Bhatti
I've this function for my Wordpress plugin uses jQuery that prints the content from the div with class "table_disp". How can I print the css style along with it.
我为我的 Wordpress 插件提供了这个函数,它使用 jQuery 打印来自类“table_disp”的 div 的内容。如何打印 css 样式。
function pop_print(){
w=window.open(null, 'Print_Page', 'scrollbars=yes');
w.document.write(jQuery('.table_disp').html());
w.document.close();
w.print();
}
Any idea?
任何的想法?
采纳答案by Diodeus - James MacFarlane
You need to include the SAME stylesheet you're using in the parent page within the pop-up. You may want to make a dummy page stub/wrapper that has your stylesheet in it, then inject your HTML.
您需要在弹出窗口的父页面中包含您正在使用的 SAME 样式表。您可能想要制作一个包含样式表的虚拟页面存根/包装器,然后注入您的 HTML。
var myStyle = '<link rel="stylesheet" href="http://mysite.com/mystyle.css" />';
w.document.write(myStyle + jQuery('.table_disp').html());
回答by Nisarg Patel
function PrintElem(elem) {
Popup(jQuery(elem).html());
}
function Popup(data) {
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title></title>');
mywindow.document.write('<link rel="stylesheet" href="http://www.test.com/style.css" type="text/css" />');
mywindow.document.write('<style type="text/css">.test { color:red; } </style></head><body>');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.print();
}
<a href="#" id="hrefPrint" onclick="PrintElem('.print_div')">Print</a>
回答by Gisheri
if you can add a plugin, the Jquery printThis plugin works great (since you're already using jQuery), and does exactly what you need. http://plugins.jquery.com/printThis/
如果您可以添加一个插件,Jquery printThis 插件会很好用(因为您已经在使用 jQuery),并且完全符合您的需要。http://plugins.jquery.com/printThis/
It makes an iframe and uses your page css plus allows for an additional css file specifically for printing, along with other things
它制作了一个 iframe 并使用您的页面 css 加上允许额外的 css 文件专门用于打印,以及其他内容
回答by Aftab Ahmed
Append Stylesheet instead
改为附加样式表
var css= '<link rel="stylesheet" href="/css/print.css" />';
var printContent = document.getElementById("printContentID");
var WinPrint = window.open('', '', 'width=900,height=650');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.head.innerHTML = css;
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();