http://jsfiddle.net/alnitak/R4rWn/
$(document).keypress(function(ev) {
if (ev.which === 97 || ev.which === 65) { // 'a' or 'A'
$('#mydiv').toggle();
}
});
我在上面有一个例子来说明我的意思,但我正在寻找更多样化的东西。就像如果您在一定时间内键入单词“example”一样,设置的 div 将显示并保留,直到再次键入“example”。我没有太多 JavaScript 知识,所以我不知道如何实现这一点。
最佳答案
这是我所做的一个实现。这绝不是最好的实现,而且我确信存在错误。人们担心当用户输入时缓冲区会被清除,但我相信您可以找到解决方法。但它应该会给你足够的想法来继续。
// Stores keys pressed in order
var buffer = [];
// Every keypress shove the key in a buffer and call the compleyKeyCheck() function which will assess the buffer
$(document).keypress(function(ev) {
buffer.push(ev.which);
console.log("Just pushed " + buffer[buffer.length - 1]);
complexKeyListen('example');
});
// Compares the buffer to the required string
function complexKeyListen(string){
var i;
for(i = 0; i < string.length; i++){
console.log("Char in buffer " + buffer[i]);
if (buffer[i] !== string.charCodeAt(i)) {
break;
}
}
if(i == string.length){
$('#mydiv').toggle();
buffer= [];
}
}
// Auto clear the buffer every ten seconds.
setInterval(function(window){
console.log('Cleared buffer');
buffer = [];}
,10000);
关于javascript - 按某些键使某些内容出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303638/