禁用输入字段中的滚动

Nes*_*tor 5 html javascript css scroll input

我有一个带有背景图像的输入字段,用于分隔框中的字母。

当我到达输入末尾时出现问题:由于光标位置放置在最后一个字母之后,输入视图向下滚动。

问题

如何避免视图在我的输入中滚动?

我尝试过添加一个“ overflow:hidden”并设置一个“ maxlength”,问题仍然存在。

编辑:一个简单的演示(我的目标是避免输入第四个字母时出现“移动效果”)

All*_*uin 1

我看到两个解决方案:

CSS解决方案

就像评论中所说,您可以稍微增加输入的宽度,以防止这种“跳跃”行为,例如:width : 202px

小提琴

JavaScript解决方案

如果您不能/不想更改输入的宽度,您可以阻止按键事件,然后检查输入值的长度。如果小于 4,则添加,否则什么也不做。

Jquery方式:

var t = $('#input-form');
t.keypress( function(event){
    //Prevent the value to be added
    event.preventDefault();
    //Regex that you can change for whatever you allow in the input (here any word character --> alphanumeric & underscore)
    var reg = /\w/g;
    //retreive the key pressed
    var inputChar = String.fromCharCode(event.which);
    //retreive the input's value length
    var inputLength = t.val().length;

    if ( reg.test(inputChar) && (inputLength < 4) ) {
        //if input length < 4, add the value
        t.val(t.val() + inputChar);
    }else{
        //else do nothing
        return;
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴

纯 JavaScript:

var t = document.getElementById('input-form');

t.addEventListener('keypress', function(event){
    //Prevent the value to be added
    event.preventDefault();
    //Regex that you can change for whatever you allow in the input (here any word character --> alphanumeric & underscore)
    var reg = /\w/g;
    //retreive the input's value length
    var inputChar = String.fromCharCode(event.which);
    //retreive the input's value length
    var inputLength = t.value.length;
    if ( reg.test(inputChar) && (inputLength < 4) ) {
        //if input length < 4, add the value
        t.value = t.value + inputChar;
    }else{
        //else do nothing
        return;
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴