2016-02-12 20 views
0

激發按Ctrl + G按鍵時,我工作的一個項目,我需要一個代碼,以刺激按鍵按Ctrl +的Javascript在Javascript

+1

你不能那樣做。你想達到什麼目的? – SLaks

+0

你想模擬一個'Ctrl + g'的結果? –

+0

你的意思是一個onkeydown,假裝它是ctrl-g被按下? –

回答

1

也有類似的問題最近:

Simulate Shift+Esc combination using JavaScript

長話短說,你可以模擬點擊按鍵和將網頁上的工作,並觸發該網頁的功能。你想要做的是使用瀏覽器的功能;模擬事件不會一直傳播到瀏覽器,它們停留在網頁上,因爲它們源於網頁。如果瀏覽器沒有用於此特定操作的API,則無法在頁面上觸發它。

編輯
看起來像谷歌翻譯有其自己的JavaScript包,你可以利用像在您的網頁任何其他庫。 Here's a tutorial.

0

試試這個:

<script> 
//global vars 
var ctrlpressed = false; 
var gpressed = false; 

document.onkeydown = function(event){ //Event listener: once any key is pressed, run this function 

    if(event.keyCode == 17){ //if CTRL is pressed, change the boolean of ctrlpressed to true. 
     ctrlpressed = true; 
    } 

    if(event.keyCode == 71){ //if G is pressed, change the boolean of ctrlpressed to true. 
     gpressed = true; 
    } 

    if (gpressed === true && ctrlpressed === true) //if both of them are pressed together, generate a message in the client's console 
    { 
    console.log("Both pressed together"); 
    } 


} 

document.onkeyup = function(event){ //Event listener: once any key is released, reset the booleans above 
    ctrlpressed = false; 
    gpressed = false; 
} 
</script> 

工作的罰款對我來說,每次我點擊按Ctrl +它CONSOLE.LOG它。

+0

我有一個按鈕,當它點擊時,它刺激Control + g的按鍵。你能解釋一下你的上面的代碼嗎?對不起,我是初學者,所以我有問題。謝謝:) – Stanimal

+0

如果你閱讀OP的評論,他希望Ctrl + G做一個特定的事情(啓用/禁用谷歌翻譯)。你的代碼會觸發Ctrl + G,但它不會觸及谷歌翻譯API。在下面看到我的回答 –

+0

Ctrl + g只是另一種在Chrome瀏覽器中搜索字詞的方法,我沒有看到它與Google翻譯有什麼關係。您無法更改Google Chrome的快捷鍵。 OP,我已經添加了更多解釋,檢查註釋(//) – RunningFromShia