开发者

jQuery how to get keypress() to listen for any pressed key that isn't what you specify

开发者 https://www.devze.com 2023-02-09 03:14 出处:网络
I\'m trying to get letters in 开发者_开发知识库a word to change color to red when I type and I want them to do it sequentially.However, I want it so that if someone types in an incorrect letter in tha

I'm trying to get letters in 开发者_开发知识库a word to change color to red when I type and I want them to do it sequentially. However, I want it so that if someone types in an incorrect letter in that word, the previous letters will lose their color. Here's how it's set up in the HTML file:

<p>Type the <span id="k">k</span><span id="a">a</span><span id="t">t</span> keys on your keyboard to change the letters red.</p>

In this example the word is "kat". Each letter changes to red as I type it. However, I want to make it so if I press any key other than "t" after the "ka", then "red" class is removed from "k" and "a". Is this possible?

    $(document).keypress(function(e) {
    switch(e.which) {
        case 107: $("#k").addClass('red');
    }

    if ($("#k").hasClass("red")) {
        switch(e.which) {
            case 97: $("#a").addClass('red');
        }
    }

    if ($("#a").hasClass("red")) {
        switch(e.which) {
            case 116: $("#t").addClass('red');
        }
    }
}); 


Live demo: http://jsfiddle.net/fZrwE/3/

HTML:

<span id="word">
    <span>H</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
</span>

JavaScript:

$(document).keypress(function(e) {
    var p = 'pressed',
        s = $('#word > span'),
        l = s.not('.' + p).first(),
        c = l.text().charCodeAt(0);

    e.which == c ? l.addClass(p) : s.removeClass(p);
});

Explanation:

The keypress handler has 4 local variables:
p is the class name for a pressed letter,
s is a jQuery collection of letters (SPAN elements inside the #word element),
l is the first SPAN from s that doesn't have the p class, ergo, that has not yet been pressed - note that this is the letter that has to be pressed next,
c is the code for that letter.

If e.which (the code for the letter that has been pressed by the user) is the same as c, then that means that the user pressed the correct letter, and this letter - which is referenced via l - will receive the p class. Otherwise, just reset the whole word, ergo, remove the p class from all the letters.

0

精彩评论

暂无评论...
验证码 换一张
取 消