打印DIV内容的最佳方法是什么?
当前回答
创建一个单独的打印样式表,隐藏除要打印的内容之外的所有其他元素。当你加载它时,使用'media="print"标记它:
<link rel=“stylesheet” type=“text/css” media=“print” href=“print.css” />
这允许您为打印输出加载一个完全不同的样式表。
如果你想强制浏览器的打印对话框出现在页面上,你可以在加载时使用JQuery这样做:
$(function() {window.print();});
或者由你想要的任何其他事件触发,比如用户点击一个按钮。
其他回答
只需使用PrintJS
let printjs = document.createElement("script");
printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
document.body.appendChild(printjs);
printjs.onload = function (){
printJS('id_of_div_you_want_to_print', 'html');
}
function printDomElement(element) {
element.classList.add("printCss");
let printId = "printId";
let name = ".printCss";
let rules = "-webkit-print-color-adjust:exact;height:100%;width:100%;position:fixed;top:0;left:0;margin:0;";
var style = document.createElement('style');
style.id = printId;
style.media = "print";
document.getElementsByTagName('head')[0].appendChild(style);
if (!(style.sheet || {}).insertRule)(style.styleSheet || style.sheet).addRule(name, rules);
else style.sheet.insertRule(name + "{" + rules + "}", 0);
window.print();
setTimeout(() => {
element.classList.remove("printCss");
let elem = document.getElementById(printId);
if (elem) elem.remove();
}, 500);
}
下面的代码复制了查询选择器目标的所有相关节点,复制了它们在屏幕上看到的样式,因为许多用于css选择器目标的父元素将会丢失。如果有很多带有很多样式的子节点,这将导致一些延迟。
理想情况下,你应该有一个打印样式表,但这是为用例,没有打印样式表插入,你希望打印在屏幕上看到。
如果您在此页的浏览器控制台中复制以下项目,它将打印此页上的所有代码片段。
+function() {
/**
* copied from https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
* @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
*/
var copyComputedStyle = function(from,to){
var computed_style_object = false;
//trying to figure out which style object we need to use depense on the browser support
//so we try until we have one
computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);
//if the browser dose not support both methods we will return null
if(!computed_style_object) return null;
var stylePropertyValid = function(name,value){
//checking that the value is not a undefined
return typeof value !== 'undefined' &&
//checking that the value is not a object
typeof value !== 'object' &&
//checking that the value is not a function
typeof value !== 'function' &&
//checking that we dosent have empty string
value.length > 0 &&
//checking that the property is not int index ( happens on some browser
value != parseInt(value)
};
//we iterating the computed style object and compy the style props and the values
for(property in computed_style_object)
{
//checking if the property and value we get are valid sinse browser have different implementations
if(stylePropertyValid(property,computed_style_object[property]))
{
//applying the style property to the target element
to.style[property] = computed_style_object[property];
}
}
};
// Copy over all relevant styles to preserve styling, work the way down the children tree.
var buildChild = function(masterList, childList) {
for(c=0; c<masterList.length; c++) {
var master = masterList[c];
var child = childList[c];
copyComputedStyle(master, child);
if(master.children && master.children.length > 0) {
buildChild(master.children, child.children);
}
}
}
/** select elements to print with query selector **/
var printSelection = function(querySelector) {
// Create an iframe to make sure everything is clean and ordered.
var iframe = document.createElement('iframe');
// Give it enough dimension so you can visually check when modifying.
iframe.width = document.width;
iframe.height = document.height;
// Add it to the current document to be sure it has the internal objects set up.
document.body.append(iframe);
var nodes = document.querySelectorAll(querySelector);
if(!nodes || nodes.length == 0) {
console.error('Printing Faillure: Nothing to print. Please check your querySelector');
return;
}
for(i=0; i < nodes.length; i++) {
// Get the node you wish to print.
var origNode = nodes[i];
// Clone it and all it's children
var node = origNode.cloneNode(true);
// Copy the base style.
copyComputedStyle(origNode, node);
if(origNode.children && origNode.children.length > 0) {
buildChild(origNode.children, node.children);
}
// Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.
iframe.contentWindow.document.body.append(node);
}
// Print the window
iframe.contentWindow.print();
// Give the browser a second to gather the data then remove the iframe.
window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
}
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')
这是一个非常老的帖子,但这里是我的更新,我使用正确的答案。我的解决方案也使用jQuery。
这一点是使用正确的打印视图,包括所有样式表的正确格式,也要在大多数浏览器支持。
function PrintElem(elem, title, offset)
{
// Title constructor
title = title || $('title').text();
// Offset for the print
offset = offset || 0;
// Loading start
var dStart = Math.round(new Date().getTime()/1000),
$html = $('html');
i = 0;
// Start building HTML
var HTML = '<html';
if(typeof ($html.attr('lang')) !== 'undefined') {
HTML+=' lang=' + $html.attr('lang');
}
if(typeof ($html.attr('id')) !== 'undefined') {
HTML+=' id=' + $html.attr('id');
}
if(typeof ($html.attr('xmlns')) !== 'undefined') {
HTML+=' xmlns=' + $html.attr('xmlns');
}
// Close HTML and start build HEAD
HTML+='><head>';
// Get all meta tags
$('head > meta').each(function(){
var $this = $(this),
$meta = '<meta';
if(typeof ($this.attr('charset')) !== 'undefined') {
$meta+=' charset=' + $this.attr('charset');
}
if(typeof ($this.attr('name')) !== 'undefined') {
$meta+=' name=' + $this.attr('name');
}
if(typeof ($this.attr('http-equiv')) !== 'undefined') {
$meta+=' http-equiv=' + $this.attr('http-equiv');
}
if(typeof ($this.attr('content')) !== 'undefined') {
$meta+=' content=' + $this.attr('content');
}
$meta+=' />';
HTML+= $meta;
i++;
}).promise().done(function(){
// Insert title
HTML+= '<title>' + title + '</title>';
// Let's pickup all CSS files for the formatting
$('head > link[rel="stylesheet"]').each(function(){
HTML+= '<link rel="stylesheet" href="' + $(this).attr('href') + '" />';
i++;
}).promise().done(function(){
// Print setup
HTML+= '<style>body{display:none;}@media print{body{display:block;}}</style>';
// Finish HTML
HTML+= '</head><body>';
HTML+= '<h1 class="text-center mb-3">' + title + '</h1>';
HTML+= elem.html();
HTML+= '</body></html>';
// Open new window
var printWindow = window.open('', 'PRINT', 'height=' + $(window).height() + ',width=' + $(window).width());
// Append new window HTML
printWindow.document.write(HTML);
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10*/
console.log(printWindow.document);
/* Make sure that page is loaded correctly */
$(printWindow).on('load', function(){
setTimeout(function(){
// Open print
printWindow.print();
// Close on print
setTimeout(function(){
printWindow.close();
return true;
}, 3);
}, (Math.round(new Date().getTime()/1000) - dStart)+i+offset);
});
});
});
}
之后你只需要这样的东西:
$(document).on('click', '.some-print', function() {
PrintElem($(this), 'My Print Title');
return false;
});
试一试。
与早期版本相比略有变化-在CHROME上测试
function PrintElem(elem)
{
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>' + document.title + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h1>' + document.title + '</h1>');
mywindow.document.write(document.getElementById(elem).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
推荐文章
- 如何禁用文本区域大小调整?
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 保留HTML字体大小时,iPhone的方向从纵向改变为横向
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- 嵌套行与自举网格系统?
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量