我有一个带有背景图像的输入字段,用于分隔框中的字母。
当我到达输入末尾时出现问题:由于光标位置位于最后一个字母之后,输入 View 向下滚动。
如何避免 View 在我的输入中滚动?
我已经尝试添加一个“overflow:hidden
”并设置一个“maxlength
”,问题仍然存在。
编辑:a simple demonstration (我的目标是避免输入第 4 个字母时的“移动效果”)
最佳答案
我看到 2 个解决方案:
CSS 解决方案
如评论中所述,您可以稍微增加输入的 with 以防止这种“跳跃”行为
喜欢:宽度: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;
}
});
纯 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;
}
});
关于javascript - 在输入字段中禁用滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498262/