打印DIV内容的最佳方法是什么?
当前回答
function printdiv(printdivname) {
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
这将打印您想要的div区域,并将内容设置为原来的内容。Printdivname是要打印的div。
其他回答
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);
}
这应该可以工作:
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
我编写了一个插件来解决这种情况。我对现有的插件不满意,开始做一些更广泛/可配置的东西。
https://github.com/jasonday/printThis
与早期版本相比略有变化-在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;
}
打开一个新窗口 打开新窗口的文档对象,并在其中写入一个简单的文档,其中只包含您已经获得的div和必要的html头文件等-您可能还希望将文档拉入样式表,这取决于您的内容是什么 在新页面中放入一个脚本来调用window.print() 触发脚本
推荐文章
- 关联数组对象上的JavaScript foreach循环
- 实例化模块失败[$injector:unpr]未知提供者:$routeProvider
- 如何在JavaScript交换两个变量
- 如何从一个变量设置一个JS对象属性名
- 在JavaScript中转换为字符串
- 在jQuery中检测输入[type=text]的值变化
- +0和-0是一样的吗?
- 转换php数组到Javascript
- 如何跳转到浏览器页面的顶部
- 确定$。Ajax错误是一个超时
- 在电子邮件消息中是否支持JavaScript ?
- 如何在JavaScript中指定Math.log()的基?
- 多重左赋值JavaScript
- 使用jQuery创建、读取和删除cookie
- 如何在单个测试基础上更改模拟实现?