当我通过键盘按默认打印按钮时,我想从网页打印div
。但我不知道该怎么办。
我尝试使用
keypress
,但如果我按下任意一个键,它就会打印出来 键盘,但如果按键对ctrl+p
,我想打印。
我尝试类似:
$(document).bind('keypress', 'ctrl+p', printContent);
function printContent(){
var restorepage = document.body.innerHTML;
var printcontent = document.getElementById("print_div").innerHTML;
document.body.innerHTML = printcontent;
window.print();
document.body.innerHTML = restorepage;
}
HTML
<h1>My Print page</h1>
<div id="print_div">
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>
如果有人给我这个想法,那么它对我有帮助。
提前致谢。
答案 0 :(得分:1)
如评论中所述,您应该查看@media print
css标记。
当任何用户执行ctrl / cmd + P时,你可以隐藏任何你不打印的元素,这样就可以节省一些墨水和时间。
答案 1 :(得分:1)
使用此代码:
<html>
<head>
<script src="http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js"></script>
<script language="javascript" type="text/javascript">
shortcut.add("ctrl+p", function() {
var myDiv = document.getElementById("ID").innerHTML;
var oldPage = document.body.innerHTML;
document.body.innerHTML =
"<html><head><title></title></head><body>" +
myDiv + "</body>";
window.print();
document.body.innerHTML = oldPage;
});
</script>
</head>
<body>
<div id="ID">
print only this div
</div>
<div>
this will NOT be printed
</div>
</body>
</html>