javascript - 在输入字段中禁用滚动

标签 javascript html css input scroll

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

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

The problem

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

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

编辑:a simple demonstration (我的目标是避免输入第 4 个字母时的“移动效果”)

最佳答案

我看到 2 个解决方案:

CSS 解决方案

如评论中所述,您可以稍微增加输入的 with 以防止这种“跳跃”行为 喜欢:宽度:202px

fiddlejs

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

fiddlejs

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

fiddlejs

关于javascript - 在输入字段中禁用滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498262/

相关文章:

javascript - 获取未知数量输入的值

javascript - 绘图 : x-axis y axis set min and max values

html - Beautifulsoup 无法从 img 标签中提取 src 属性

css - css3 matrix3d 第四列背后的精确数学是什么?

html - 如何在保持嵌套列表可见的同时隐藏嵌套列表的父级?

javascript - 将页面上的 JSON 数据显示为可展开/可折叠列表

javascript - Jquery.clone() 函数

javascript - HTML 事件属性和使用 HTML DOM 分配事件有什么区别?

jquery - CSS 多个 div 溢出

css - 无法将按钮定位到 flex 容器的底部(导入到 WordPress 时)