javascript - 如何使用 document.write 函数在 printview 中动态加载图像
问题描述
我正在尝试使用document.write
函数动态加载图像。请在下面找到代码。图片有时会加载,有时不显示。
var mywindow = window.open('', 'PRINT', 'height=400,width=600');
mywindow.document.write('<html><head><title>'+"Contract Approval Form"+'</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<div id="headerLogo"></div>');
mywindow.document.write('<div id="watermarkDiv"></div>');
mywindow.document.write('<div style="margin-top:50px;" id="content">' +printContent+ '</div>');
var img = mywindow.document.createElement('img');
img.setAttribute('src', 'mylogo.png');
mywindow.document.getElementById("headerLogo").appendChild(img);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
解决方案
这是关于等待内容加载
<script>
var printContent = '<h1>Hello World</h1>';
var mywindow = window.open('about:blank', 'PRINT', 'height=400,width=600');
//~ mywindow.onload = function() {
mywindow.document.write('<html><head><title>'+"Contract Approval Form"+'</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<div id="headerLogo"></div>');
mywindow.document.write('<div id="watermarkDiv"></div>');
mywindow.document.write('<div style="margin-top:50px;" id="content">' +printContent+ '</div>');
var img = mywindow.document.createElement('img');
img.setAttribute('src', 'mylogo.png');
img.onload = function() {
// now you can print, need to wait for image to load - which connotes you need to work out how to wait for all content to load
mywindow.focus();
mywindow.print();
}
mywindow.document.getElementById("headerLogo").appendChild(img);
mywindow.document.write('</body></html>');
</script>
推荐阅读
- python-3.x - 如何创建一个列,该列显示具有“对象”数据类型的列中每个值的数据类型
- git - 从 gitlab 存储库而不是本地目录导入 terraform 模块会产生略有不同的 terraform 计划输出
- r - 删除重复出现的 GitHub 凭据提示
- sql - 在 presto 中优化窗口查询
- unity3d - Unity:从 FBX 文件中获取每一帧的关节旋转
- c# - Specflow - 如何在下一步中将响应作为变量传递
- raspberry-pi3 - 如何更改 pjsip 中的默认音频设备
- azure-aks - Azure Kubernetes 集群安全
- pandas - 将表格 pandas DataFrame 转换为嵌套的 pandas DataFrame
- javascript - JS 异步不起作用 | 由于背景图像导致的 LCP 问题,这是用 JS 设置的