简体   繁体   中英

JavaScript: Using up and down arrows on input text

I have a problem with javascript keys, Chrome (only testing on chrome right now) does not recognise up and down arrows on text input, as it has this default behaviour in which it changes the caret position. My code is as follows:

 if (!e) e = window.event;
var keyCode = e.keyCode || e.which;

if (keyCode == '13'){ //enter key
    //some code that works
    return false;

}else if(keyCode=='38'){ //up key
    //some other code that doesn't work
    return false;

}else if(keyCode=='40'){ //down key
    //some other code that doesn't work
    return false;
}

If anyone has a solution I will greatly appreciate it. Thank you!

Hard to see where the code is from (an keypress listener I guess). As you can see below and this fiddle (and as Teemu also pointed out), keypress won't get called on arrow keys.

On another note, use event.preventDefault() to prevent the default behaviour of the browser, in your case the placing of the caret, also your listener functions can except an event object as a parameter.

var listener = function (e) {
    e = e || window.event;

    alert(e.type);
    var keyCode = e.keyCode || e.which;

    if(keyCode=='38' || keyCode=='40'){ //arrow key
        alert("arrow!");
        e.preventDefault();
        return false;

    }        
}

var elem = document.getElementById('input');

elem.addEventListener('keydown', listener, false);

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