问题
I have a document which pops up on the site within a JQuery Modal Box. The document has a print button at the end which just prints the document in the Pop-Up Box.
I am looking to find a solution that I can print the pop-up box by pressing Ctrl+P. Right now Ctrl+p prints all the page including the background ... I am just hoping to find a solution which helps me print the document in the pop-up only.
My JQuery Modal Box is in iFrame and is shown in the following way:-
<div id="frameContainer">
<iframe id="lightboxFrame" width="950px" scrolling="auto" height="500px">
<!DOCTYPE html>
<html>
<head>
<body> (Whole Document in a Div) </body>
...
This is the DIV in the pop-up HTML that prints the pop-up document.
<div id="edit-actions" class="form-actions form-wrapper">
<input id="print-submit" class="form-submit" value="Print this Survey" name="print" onclick="printAssessment()" type="button" />
</div>
This is what I did:-
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '80')) { //cntrl + p
event.preventDefault();
printAssessment();
}
});
function printAssessment() {
//alert("Print the little page");
window.print();
}
The function is definitely being called when I press Ctrl+P but it still prints the whole page. I want that it prints only the Modal Box. Weirdly, when I press the print button inside the Modal Box, which uses the same function, it prints correctly.
Thanks,
FIRST EDIT:-
Partially working now.
When I changed the function of PrintAssessment() to the following, it works:-
function printAssessment() {
window.frames["lightboxFrame"].focus();
window.frames["lightboxFrame"].print();
}
But, the weird thing is that It prints when I click Ctrl+P only the first time. When I try to print again, it keeps giving me this error:-
Uncaught TypeError: Cannot call method 'print' of undefined
or
Uncaught TypeError: Cannot call method 'focus' of undefined
Thanks.
回答1:
Instead of :
window.print();
You can print the content of the iframe like following :
$('#lightboxFrame')[0].contentWindow.print();
Put the code bellow in your function printAssessment()
来源:https://stackoverflow.com/questions/16304538/trigger-ctrlp-printing-for-a-jquery-modal-box-through-keyboard