[英]Simulate a key press without targeting an element?
我需要模擬一個按鍵。 但是我剛剛能夠找到這個:
var press = jQuery.Event("keypress");
press.ctrlKey = false;
press.which = 75;
$("whatever").trigger(press);
其中“無論如何”是輸入字段或其他內容。 但是,我不需要定位任何元素。 如何在不定位任何元素的情況下模擬按鍵(具體來說是“ k”鍵)?
如果您不想針對任何元素,則必須直接針對body
,這樣,任何鍵都應觸發您想要的對象
$(document).ready(function(){ $("body").keypress(function(){ alert('hey'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
瞄准身體會使您毫無目標感。
function showChar(e) { alert("Key Pressed: " + String.fromCharCode(e.charCode) + "\\n" + "charCode: " + e.charCode); }
<body onkeypress="showChar(event);">
像這樣做:
$('body').keypress(function(e){
if ( e.which == 75 ) {
alert('hey k was pressed');
}
});
看看這個字符代碼列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.