打印DIV内容的最佳方法是什么?
当前回答
从这里https://forums.asp.net/t/1261525.aspx
<html>
<head>
<script language="javascript">
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
<title>div print</title>
</head>
<body>
//HTML Page //Other content you wouldn't like to print
<input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">
<div id="div_print">
<h1 style="Color:Red">The Div content which you want to print</h1>
</div>
//Other content you wouldn't like to print //Other content you wouldn't like to print
</body>
</html>
其他回答
下面的代码复制了查询选择器目标的所有相关节点,复制了它们在屏幕上看到的样式,因为许多用于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')
这应该可以工作:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
我知道这是一个老问题,但我用jQuery解决了这个问题。
function printContents(id) {
var contents = $("#"+id).html();
if ($("#printDiv").length == 0) {
var printDiv = null;
printDiv = document.createElement('div');
printDiv.setAttribute('id','printDiv');
printDiv.setAttribute('class','printable');
$(printDiv).appendTo('body');
}
$("#printDiv").html(contents);
window.print();
$("#printDiv").remove();
}
CSS
@media print {
.non-printable, .fancybox-outer { display: none; }
.printable, #printDiv {
display: block;
font-size: 26pt;
}
}
虽然@BC的答案最好打印一页。
但要打印多页A4大小的同时按ctrl+P以下解决方案可能会有所帮助。
@media print{
html *{
height:0px!important;
width:0px !important;
margin: 0px !important;
padding: 0px !important;
min-height: 0px !important;
line-height: 0px !important;
overflow: visible !important;
visibility: hidden ;
}
/*assing myPagesClass to every div you want to print on single separate A4 page*/
body .myPagesClass {
z-index: 100 !important;
visibility: visible !important;
position: relative !important;
display: block !important;
background-color: lightgray !important;
height: 297mm !important;
width: 211mm !important;
position: relative !important;
padding: 0px;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
orphans: 0!important;
widows: 0!important;
overflow: visible !important;
page-break-after: always;
}
@page{
size: A4;
margin: 0mm ;
orphans: 0!important;
widows: 0!important;
}}
公认的解决方案不起作用。Chrome打印了一个空白页面,因为它没有及时加载图像。这种方法是有效的:
编辑:看来接受的解决方案在我发布后被修改了。为什么会投反对票?这个解决方案也同样有效。
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
推荐文章
- 给一个数字加上st, nd, rd和th(序数)后缀
- 如何以编程方式触发引导模式?
- setTimeout带引号和不带括号的区别
- 为什么我的CSS3媒体查询不能在移动设备上工作?
- 在JS的Chrome CPU配置文件中,'self'和'total'之间的差异
- 用javascript检查输入字符串中是否包含数字
- 如何使用JavaScript分割逗号分隔字符串?
- 在Javascript中~~(“双波浪号”)做什么?
- 谷歌chrome扩展::console.log()从后台页面?
- 下一个元素的CSS选择器语法是什么?
- 未捕获的SyntaxError:
- [].slice的解释。调用javascript?
- 在jQuery中的CSS类更改上触发事件
- jQuery日期/时间选择器
- 我如何用CSS跨浏览器绘制垂直文本?