javascript控制键盘right键在input中将光标右移

2025-01-06 18:11:58
推荐回答(2个)
回答1:

onkeydown事件里面写

 

如下,我简单写了一下:




    function whichButton(obj, event) {
        var keycode = event.which || event.keyCode;
        //按下了right键
        if (keycode == 39) {
            //如果光标的位置到了6,则按键不生效
            if (getCursorPosition(obj) >= 6) {
                return false;
            }
        }
    }
    //判断光标的索引
    function getCursorPosition(obj) {
        var cursurPosition = -1;
        if (obj.selectionStart) {
            cursurPosition = obj.selectionStart;
        } else {
            var range = document.selection.createRange();
            range.moveStart("character", -obj.value.length);
            cursurPosition = range.text.length;
        }
        return cursurPosition;
    }



    

回答2:

在js中这么写

var num = 0;
input.onkeyup = function (e) {
e = e || window.event;
if (e.which === 39 && num ++ >= 5) {
return false;
}
}