я использовал Bill Paetzke
ответ, чтобы напечатать div, содержащий изображения, но он не работал с Google 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>
также, если кому-то просто нужно напечатать 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>
Я надеюсь, что это может кому-то помочь