我試圖在多次按下某個按鍵時運行一個功能。我怎樣才能在JavaScript中做到這一點?檢查一個按鍵是否被按下兩次
我想這樣
if (e.keyCode == 27) {
if (e.keyCode == 27) {
alert("pressed two times");
}
}
我試圖在多次按下某個按鍵時運行一個功能。我怎樣才能在JavaScript中做到這一點?檢查一個按鍵是否被按下兩次
我想這樣
if (e.keyCode == 27) {
if (e.keyCode == 27) {
alert("pressed two times");
}
}
如果你不介意者均基於時間的關鍵壓制,存儲上次記者在一個變量和比較:
var lastKeyCode;
if (e.keyCode == 27) {
if (e.keyCode == lastKeyCode;) {
alert("pressed two times");
} else {
lastKeyCode = e.keyCode;
}
}
如果你想檢查鍵將整個單詞或句子按下兩次,然後將每個關鍵代碼放入數組中,並且每次都與數組元素進行匹配,如果存在則表示按下了兩次。
var KeyCodes;
if (e.keyCode == 27) {
if (jQuery.inArray(e.keyCode, KeyCodes)) {
//mean two time exist
} else {
KeyCodes.push(e.keyCode);
}
}
你可以定義一個全局變量,做這樣的
var pressCount = 0; // global
if (e.keyCode == 27) {
pressCount++;
if (pressCount == 2) {
alert("pressed two times");
}
}
如果(pressCount == 2)將'pressCount'重置爲'0'' – halex 2015-03-31 08:10:45
你不能做同步那樣。由於沒有doublekeypress事件,所以您必須通過記住最後一次按鍵和按下它的時間來檢測它。 – Touffy 2015-03-31 08:02:50
可能重複[Javascript - 檢查鍵是否在5秒內按兩次](http://stackoverflow.com/questions/23820862/javascript-check-if-key-was-pressed-twice-within-5-secs) – D4V1D 2015-03-31 08:02:52