附加样式表链接以在jQuery click()事件上触发打印 [英] Append stylesheet link for printing triggered on jQuery click() event
问题描述
我的头部分具有一个具有media='screen'
属性的css链接,然后我想动态地链接另一个具有media='print'
属性的css文件.
I have one css link on the head section that has media='screen'
attribute, then I want to link the other css file that has media='print'
attribute dynamically.
我为此解决了这个问题.
and I do this for the solution.
$("div#alert").click(function(){
$('head')
.append("<link rel='stylesheet' href='css/alert.css' media='print' />");
window.print();
});
但是..当我运行该代码时,输出只是基于media='screen'
css打印.
But.. When I ran that code, the output just printed based on the media='screen'
css.
然后我使用相同的代码再次尝试,我单击了div元素,并在出现打印对话框时,单击了取消按钮,然后再次单击了div元素..然后这次单击了确定按钮. media='print'
正在工作...那么我应该怎么处理window.print()
?
Then I try again with the same code, I clicked the div element and when the print dialog box appear, I clicked the cancel button, then I clicked the div element again.. then clicked the ok button this time.. the media='print'
is working... So what do I have to do with the window.print()
?
推荐答案
也许您调用window.print()的时间过早(甚至在下载打印样式表之前)-尝试以下操作:
Maybe you are calling window.print() too early (before the print stylesheet has even been downloaded) - try this:
$("div#alert").click(function(){
$('head')
.append("<link rel='stylesheet' href='css/alert.css' media='print' />");
setTimeout(function() {
window.print();
}, 1000);
});
一种更优雅的解决方案是异步加载样式表,将其插入头部,然后在AJAX请求的回调中调用print()函数.
A more elegant solution would be to load the stylesheet asynchronously, insert it in the head, and then call the print() function in the callback of the AJAX request.
这篇关于附加样式表链接以在jQuery click()事件上触发打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!