gpt4 book ai didi

javascript - 打印功能在 chrome 中不起作用

转载 作者:太空狗 更新时间:2023-10-29 16:52:26 25 4
gpt4 key购买 nike

我的网站中有一个 print() 函数,用于打印网站的特定部分。它在 Firefox 甚至 Internet explorer 上运行良好,但在 chrome 上运行不佳。它会打开对话窗口并获取页数,但无法获取内容(在 chrome 中)。

我的代码如下:

<a href="#" onclick="PrintElem('#press_releas11')"><img src="images/print_icon.png" width="35" height="23" /></a>

<div class="blog_post" id="press_releas11">
<div class="post_title"><h3>title here</h3></div>
<div class="post_article">content here</div>
</div>

脚本:

<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>PressReleases</title>');
mywindow.document.write('<link rel="stylesheet" href="css/main.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('data');
mywindow.document.write('</body></html>');

mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10

mywindow.print();
mywindow.close();

return true;
}

</script>

最佳答案

Chrome 似乎不喜欢 document.write()。在写入文档然后调用 mywindow.print() 之后添加 1000 毫秒的 setTimeout 会有所帮助,但是因为这不是很实用而且您似乎已经在使用 jQuery ,这是一个可行的解决方案:

https://jsfiddle.net/2n88pxee/

适用于 Chrome 和 Firefox,但是我还没有尝试过所有其他浏览器。

编辑:这里是评论中要求的代码

function PrintElem(elem)
{
Popup($(elem).html());
}

function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');

mywindow.document.head.innerHTML = '<title>PressReleases</title><link rel="stylesheet" href="css/main.css" type="text/css" />';
mywindow.document.body.innerHTML = '<body>' + data + '</body>';

mywindow.document.close();
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();

return true;
}

关于javascript - 打印功能在 chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com