JavaScript:在输入文本上使用向上和向下箭头

时间:2022-02-23 20:43:34

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:

我的javascript键有问题,Chrome(目前仅在chrome上测试)无法识别文本输入上的向上和向下箭头,因为它具有更改插入位置的默认行为。我的代码如下:

 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!

如果有人有解决方案,我会非常感激。谢谢!

1 个解决方案

#1


1  

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.

很难看到代码的来源(我猜是一个按键监听器)。正如你在下面看到的这个小提琴(和Teemu也指出的那样),按键不会被箭头键调用。

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.

另请注意,使用event.preventDefault()来防止浏览器的默认行为,在您放置插入符号的情况下,您的侦听器函数也可以将事件对象作为参数。

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);

#1


1  

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.

很难看到代码的来源(我猜是一个按键监听器)。正如你在下面看到的这个小提琴(和Teemu也指出的那样),按键不会被箭头键调用。

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.

另请注意,使用event.preventDefault()来防止浏览器的默认行为,在您放置插入符号的情况下,您的侦听器函数也可以将事件对象作为参数。

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);