简体   繁体   中英

Keydown function not working with input?

I've got a simple log-in page that I hid an Easter-egg on for the team. Basically, it's a mostly blank page with:

<form id="X" method="post" action="Y">
    <input id="Z" name="Z" type="text" maxlength="99" />
    <button type="submit" class="">Make the Jump</button>
</form>

The Easter-egg is:

function getFun() {
  var max = 1971;
  var rando = Math.floor(Math.random() * Math.floor(max));
  var getFunURL = 'https://xkcd.now.sh/' + rando;
  var comicHTML;
  var GetComic = $.ajax({
    url: getFunURL,
    method: 'get',
  })
  .done(function(data) {
    var title = data.safe_title;
    var imgURL = data.img;
    comicHTML = '<img src="' + imgURL + '" />';
  })
  .fail(function() {
    comicHTML = '<div>No dice on the comic. It failed to load.</div>';
  })
  .always(function() {
    $("#easterEgg").html(comicHTML);
    $("#easterEgg").show();
  });
}
var allowedKeys = {
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  65: 'a',
  66: 'b'
};
var konamiCode = ['up', 'up', 'down', 'down', 'left', 'right', 'left', 'right', 'b', 'a'];
var konamiCodePosition = 0;
$(document).keydown(function(e) {
  var key = allowedKeys[e.keyCode];
  var requiredKey = konamiCode[konamiCodePosition];
  if (key == requiredKey) {
    konamiCodePosition++;
    if (konamiCodePosition == konamiCode.length) {
      activateCheats();
      konamiCodePosition = 0;
    }
  } else {
    konamiCodePosition = 0;
  }
});
function activateCheats() {
  getFun();
}

When clicking into the blank space of the page (removing the cursor from being inside the input) and executing Konami, the comic loads. However, when the cursor is inside of the input, executing Konami does nothing.

Why would the .keydown function not work when cursor is inside the input?

use this

$("#Z").keydown(function(e) {
// write code here
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM