jquery Javascript监听键盘,在文本输入时

h7wcgrx3  于 2022-12-22  发布在  jQuery
关注(0)|答案(5)|浏览(178)

我想显示弹出窗口,如果用户输入文本,无论在网站上,我看到javascript有关键的侦听器,但什么是最好的方式,如果我想显示弹出窗口时,用户写“ShowMePopup”?
我写这个脚本是为了测试

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; 
  }
  
  var name = event.key;
  var code = event.code;

  console.log(`Key pressed ${name} \r\n Key code value: ${code}`);

  switch (event.key) {
    case "ArrowDown":
      alert('arrow down')
      break;
    case "Shift + S + h + o + w + Shift + M + e + Shift + P + o + p + u + p":
      alert('Secret Popup')
      break;
    default:
      return;
  }

  event.preventDefault();
}, true);

我已尝试添加大小写

case "Shift + S + h + o + w + Shift + M + e + Shift + P + o + p + u + p":

但是行不通,有什么办法吗?

csbfibhn

csbfibhn1#

当一个键被按下时,将它推入一个数组。然后,检查数组中最后11个项目(所需组合键的长度)是否为您的组合键:

const keysPressed = [];
const popupKeyCombo = ['Shift', 'S', 'h', 'o', 'w', 'Shift', 'M', 'e', 'Shift', 'P', 'o', 'p', 'u', 'p'];
window.addEventListener("keydown", e => {
    keysPressed.push(e.key);
    if(keysPressed.slice(-popupKeyCombo.length).join() === popupKeyCombo.join()){
        alert('Secret Popup');
    }
});

并考虑添加额外的逻辑以保持数组的大小合理。

szqfcxe2

szqfcxe22#

你可以通过在监听器函数的外部创建一个存储变量来解决这个问题,并将每个按键事件存储在里面。但是,要注意按键的时间,因为按住shift的时间越长,就会触发多个按键事件。但是,你应该让它工作。

let storage = "";

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; 
  }
  storage += event.key;
  console.log(storage);
  
  if(storage.includes("ShiftShowShiftMeShiftPopup")){
  alert("Surprise");
  storage = "";
  }
  event.preventDefault();
}, true);
6ioyuze2

6ioyuze23#

您可以跟踪keydown事件每次出现时键入的内容,然后在预期文本和到目前为止捕获的内容之间做减法。
一旦捕获偏离预期,捕获的字符串将被重置。
在键入每个字符时,演示程序将在控制台上打印预期的完整字符串,自最近一次重置以来捕获的内容以及仍然缺少的内容。
当密码被正确捕获时,函数secretUnlocked被触发。

此解决方案不会有无限增长的缓冲区,而只有捕获的字符串,只要它与预期的输入匹配。一旦键入的字符串出现分歧,缓冲区将被重置,并使用最小的内存量。

let captured = "";
let expected = "ShowMePopup";

//substracts captured to expected and returns the text fragment still missing
function diff(expected, capture){
 const split = expected.split(capture);
 if(split[0].length > 0 || split.length > 2)
  return expected;
 else
  return split[1];
}

document.addEventListener('keydown', function(event) {  

  //character allowed (this is a lazy trick to exclude special keys like shift, ctrl...)
  const allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
  if(!allowedChars.split('').includes(event.key)){  
    return;
  }
  
  //appends the latest typed char to the captured string
  captured += event.key;    
  const stillExpecting = diff(expected, captured);

  //if stillExpecting is still the same as expected, resets the captured part
  if(stillExpecting === expected)
    captured = '';
  
  console.log(`expecting: ${expected} .. so far: ${captured} .. still expecting: ${stillExpecting}`);
  
  //if stillExpecting has zero length, the condition is met
  if (stillExpecting.length === 0){
    secretUnlocked();
  }
});

function secretUnlocked(){
  console.log('Secret Unlocked');
}
Type the secret passphrase while the document has focus...
yptwkmov

yptwkmov4#

哇,这么多代码。
这个也行

let text = "";
const phrase = "ShowMePopup";
window.addEventListener("keydown", e => {
  const key = event.key;
  if (key.length !==1) return; // ignore shift etc. The shifted char is in the next key
  text += key;
  if (text.indexOf(phrase) != -1) {
    console.log("Show popup");
    text = ""; // to handle ShowMePopupShow....
  }  
  else if (phrase.indexOf(key) === -1) text = ""; //reset
});
axr492tv

axr492tv5#

你是说一个像这样弹出的钥匙探测器?试试这个代码。

function showKC(event) {
var x = event.keyCode;
var y = event.key;
document.getElementById("charcode").innerHTML = "Key: "+y+" Code: "+x;
}

function CheckPop() {
    var smp = "ShowMePopup";
    var text = document.getElementById("t1");
    if (text.value == smp) {
    alert(smp);
    }

}
Just type on keyboard <input type="text" id="t1" value="" onkeyup="showKC(event), CheckPop()"/>
<div id="charcode"></div>

相关问题