2016-03-10 53 views
-1

當我通過鍵盤按下默認打印按鈕時,我想從網頁打印div。但我不知道該怎麼做。通過按ctrl + p從頁面打印特定的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> 

如果有任何人給我的想法那麼這將是對我有幫助。

在此先感謝。

+2

爲什麼不使用的打印介質,以確保除了你想要的一切DIV CSS規則是'顯示:none'? – eggyal

+0

我不知道這件事。如果有任何參考,請提供。 –

+0

@FrayneKonok https://developer.mozilla.org/en-US/docs/Web/CSS/@media使用「@media print」,然後使所有非必需元素「display:none」。 –

回答

1

正如評論中所說,你應該看看@media print css標籤。 當任何用戶執行ctrl/cmd + P時,您可以隱藏任何您不想打印的元素,因此可以節省一些墨水和時間。

+0

奧基得到它,我會在某個時候做到這一點。 –

0

使用此代碼:

<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> 
相關問題