Prevent default behavior in text input while pressing arrow up

不打扰是莪最后的温柔 提交于 2019-11-29 22:56:28

To preserve cursor position, backup input.selectionStart before changing value.

The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.

var ignoreKey = false;
var handler = function(e)
{
    if (ignoreKey)
    {
        e.preventDefault();
        return;
    }
    if (e.keyCode == 38 || e.keyCode == 40) 
    {
        var pos = this.selectionStart;
        this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);        
        this.selectionStart = pos; this.selectionEnd = pos;

        ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
        e.preventDefault();
    }
};

input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);

I found that a better solution is just to return false; to prevent the default arrow key behavior:

input.addEventListener("keydown", function(e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false;
}, false);

Actually, there is a better and simpler method to do this job.

$('input').bind('keydown', function(e){
    if(e.keyCode == '38' || e.keyCode == '40'){
        e.preventDefault();
    }
});

Yes, it is so easy!

I tested the code and it seems that it cancels the event but if you don't press the arrow for very short time - it fires keypress event and that event actually moves cursor. Just use preventDefault() also in keypress event handler and it should be fine.

Probably not. You should instead seek for a solution to move the cursor back to the end of the field where it was. The effect would be the same for the user since it is too quick to be perceived by a human.

I googled some and found this piece of code. I can't test it now and it is said to not to work on IE 6.

textBox.setSelectionRange(textBox.value.length, textBox.value.length);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!