打印DIV内容的最佳方法是什么?
当前回答
我认为有更好的解决办法。让你的div打印覆盖整个文档,但只在打印时:
@media print {
.myDivToPrint {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
其他回答
注意:从下面提到的插件编写到现在已经有13年了,就像评论中提到的那样。它不再工作,因为改变了API在jQuery。随意分叉和添加一个拉请求!
虽然这是@gabe说的, 如果你正在使用jQuery,你可以使用我的printElement插件。
这里有一个示例,以及关于插件的更多信息。
使用方法相当简单,只需用jQuery选择器抓取一个元素并打印它:
$("#myDiv").printElement();
我希望这能有所帮助!
创建一个单独的打印样式表,隐藏除要打印的内容之外的所有其他元素。当你加载它时,使用'media="print"标记它:
<link rel=“stylesheet” type=“text/css” media=“print” href=“print.css” />
这允许您为打印输出加载一个完全不同的样式表。
如果你想强制浏览器的打印对话框出现在页面上,你可以在加载时使用JQuery这样做:
$(function() {window.print();});
或者由你想要的任何其他事件触发,比如用户点击一个按钮。
我使用Bill Paetzke的答案打印一个div包含图像,但它不能与谷歌chrome
我只需要添加这一行myWindow.onload=function(){使它工作,这里是完整的代码
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
<script type="text/javascript">
function PrintElem(elem) {
Popup($(elem).html());
}
function Popup(data) {
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>
如果有人只是需要打印一个带有id的div,他不需要加载jquery
这里是做这件事的纯javascript代码
<html>
<head>
<script type="text/javascript">
function PrintDiv(id) {
var data=document.getElementById(id).innerHTML;
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>
我希望这能帮助到一些人
我认为目前提出的解决方案有以下缺点:
CSS媒体查询解决方案假设只有一个div要打印。 javascript解决方案只适用于特定的浏览器。 破坏父窗口内容并重新创建会造成混乱。
我改进了上面的解决方案。下面是我测试过的一种方法,效果非常好,有以下好处。
适用于所有浏览器,包括IE, Chrome, Safari和firefox。 不会破坏和重载父窗口。 可以在页面上打印任意数量的DIV。 使用HTML模板避免容易出错的字符串连接。
注意事项:
必须在新创建的窗口上有一个onload="window.print()"。 不要从父类调用targetwindow.close()或targetwindow.print()。 确保执行targetwindow.document.close()和target.focus() 我使用的是jquery,但你也可以使用简单的javascript做同样的技术。 你可以在这里看到它的行动https://math.tools/table/multiplication。通过单击框头上的打印按钮,可以分别打印每个表。
<script id="print-header" type="text/x-jquery-tmpl"> <html> <header> <title>Printing Para {num}</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style> body { max-width: 300px; } </style> </header> <body onload="window.print()"> <h2>Printing Para {num} </h2> <h4>https://math.tools</h4> </script> <script id="print-footer" type="text/x-jquery-tmpl"> </body> </html> </script> <script> $('.printthis').click(function() { num = $(this).attr("data-id"); w = window.open(); w.document.write( $("#print-header").html().replace("{num}",num) + $("#para-" + num).html() + $("#print-footer").html() ); w.document.close(); w.focus(); //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window. ///w.close(); Don't do this otherwise chrome won't work }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a> <a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a> <p class="para" id="para-1"> Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p class="para" id="para-2"> Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
创建一些通用的东西用于任何HTML元素
HTMLElement.prototype.printMe = printMe;
function printMe(query){
var myframe = document.createElement('IFRAME');
myframe.domain = document.domain;
myframe.style.position = "absolute";
myframe.style.top = "-10000px";
document.body.appendChild(myframe);
myframe.contentDocument.write(this.innerHTML) ;
setTimeout(function(){
myframe.focus();
myframe.contentWindow.print();
myframe.parentNode.removeChild(myframe) ;// remove frame
},3000); // wait for images to load inside iframe
window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
希望这能有所帮助。
推荐文章
- 如何禁用文本区域大小调整?
- 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每次循环范围之外的变量