如何使用javascript,jquery等创建打印模式 [英] how to create a print modal using javascript, jquery etc
问题描述
假设我在几页和每当用户点击时都有一个打印按钮。
它将以模态弹出内容并可以从那里打印。任何想法都将受到赞赏。
let say i have a print button on couple of pages and whenever user click . it will pop up the content in a modal and can print from there.Any idea will be appreciated.
我有几页带打印按钮。当用户点击它时需要在模态中输出内容而不是从该模态打印。
I have couple of page with a print button . when user click it need to pul that content in a modal and than print from that modal.
推荐答案
我不能写你现在的代码,但我可以让你走在正确的轨道上..
I can't write the code for you right now but I can put you on the right track..
你需要使用jquery来获取你想要打印的内容(可能 $('body')。html();
)然后创建你的模态div弹出窗口并将iframe添加到模态div中。然后添加到iframes主体(通过 $('iframe')。document.body.append();
)打印内容。然后,在iframe上调用 print
( $('iframe')。window.print;
)
You need to use jquery to get the contents you want to print (likely $('body').html();
) then create your modal div popup and add an iframe into the modal div. Then add to the iframes body (via $('iframe').document.body.append();
) the print content. Then, call print
on the iframe ($('iframe').window.print;
)
请告诉我这是否有意义?
Let me know if this makes sense?
编辑:以下是一些使用的示例代码我相信你想要什么。 (确保在此javascript代码之前包含jquery)
EDIT: Here is some example code working with what I believe you want. (make sure you include jquery before this javascript code)
<body>
<script>
$(document).ready(function(){
$('#printmodal').click(function(){
// variables
var contents = $('#printable').html();
var frame = $('#printframe')[0].contentWindow.document;
// show the modal div
$('#modal').css({'display':'block'});
// open the frame document and add the contents
frame.open();
frame.write(contents);
frame.close();
// print just the modal div
$('#printframe')[0].contentWindow.print();
});
});
</script>
<style>
#modal {
display: none;
width: 100px;
height: 100px;
margin: 0 auto;
position: relative;
top: 100px;
}
</style>
<!-- Printable div (or you can just use any element) -->
<div id="printable">
<p>This is</p>
<p>printable</p>
</div>
<!-- Print link -->
<a id="printmodal" href="#">Print Me</a>
<!-- Modal div (intially hidden) -->
<div id="modal">
<iframe id="printframe" />
</div>
</body>
jsfiddle: http://jsfiddle.net/tsdexter/ke2rqt97/
jsfiddle: http://jsfiddle.net/tsdexter/ke2rqt97/
这篇关于如何使用javascript,jquery等创建打印模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!