Javascript/jQuery Keypress logging

前端 未结 7 1744
日久生厌
日久生厌 2020-12-30 14:34

I would like to be able to log the key presses on a specific page, trying to implement an \'Easter egg\' type functionality where when the correct keys are pressed in the co

7条回答
  •  温柔的废话
    2020-12-30 14:48

    Well, even though another answer has been accepted, I'm going to throw one out there anyway.

    $(document).ready(function() {
    
        var easterEgg = 'egg';
        var eggLength = easterEgg.length;
        var keyHistory = '';
        var match;
            $(document).keypress(function(e) {
                keyHistory += String.fromCharCode(e.which)
                match = keyHistory.match(easterEgg); 
                if(match) {
                    alert(match);
                    keyHistory = match =  '';
                } else if (keyHistory.length > 30) {
                    keyHistory = keyHistory.substr((keyHistory.length - eggLength - 1));
                }
            });
    });
    

    When you ultimately type 'egg' (for this example), you will get an alert, and the key history will reset.

    EDIT: Updated the code to truncate the string if it gets too long.

提交回复
热议问题