2014-09-05 42 views
0

我想寫這將提供HTML編輯通過contenteditable和本地保存結果的用戶腳本上...如何調用一個函數,當一個鍵被按下用純JavaScript整個頁面

我想要在按下單個按鍵時激活它(如§作爲示例)頁面上的任何地方(使整個頁面可編輯)

目前,我tried a minimal subset其中功能是通過CTRL + S叫:

$("body").keydown(function (event) { 
    // Only Ctrl-S and Command-S (19) 
    if (!(String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) 
    return true; 

    document.location = 'data:text/attachment;,' + document.documentElement.innerHTML; 

    event.preventDefault(); 
    return false; 
}); 

,但沒有追加異常......和Opera蜻蜓沒有表現出任何異常(腳本加載在調試器) ...

回答

0
<script> 
window.addEventListener("keydown",doKeyDown,false); 

function doKeyDown(e) { 
    switch(§.keyCode) { 
     case 167: 
     document.location = 'data:text/attachment;,' + document.documentElement.innerHTML; 
     break; 
    } 

} 


</script> 
+0

在這種情況下,87 W鍵。我無法找到§的關鍵代碼。 – Brendan 2014-09-05 22:57:30

+0

0'function doKeyDown(e){ console.log(e.keyCode); }' – Kaiido 2014-09-05 23:05:19

0

要使文檔編輯,你可以使用:

document.querySelector('html').setAttribute('contenteditable', ''); 

這是確定等價的:

<html contenteditable> 

設置document.location到文檔的innerHTML物業將打破綁定到頁面上的事件任何JavaScript。

這是一個適用於Chrome的完整版本。

var isEditable = false; 
document.addEventListener('keydown', function(e) 
{ 
    if (isEditable) 
    return; 

    if (String.fromCharCode(e.which).toLowerCase() == 's' && e.ctrlKey) 
    { 
    document.querySelector('html').setAttribute('contenteditable', ''); 
    isEditable = true; 
    } 
}, false); 

要了解更多關於鍵盤事件,試試這個代碼在JavaScript控制檯:

document.addEventListener('keydown', function(e) { console.dir(e); }, false); 
+0

'document.location ='data:text/attachment ;,'+ document.documentElement.innerHTML;'的目的是保存html文件的編輯版本。 – user2284570 2014-09-05 23:11:33

+0

那麼你的代碼是不是完全工作?設置位置失敗,還是您的按鍵不被處理? – 2014-09-05 23:15:11

+0

我不知道...因爲什麼都沒有發生。我只想說在你的回答中你寫錯了''document.querySelector('html')。setAttribute('contenteditable','');''''if''語句裏面。您的功能正常工作,但這不是我想要使用特殊擊鍵的原因。 – user2284570 2014-09-05 23:16:48

相關問題