【问题标题】:Disable scroll in input field禁用输入字段中的滚动
【发布时间】:2015-11-03 11:43:07
【问题描述】:

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

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

The problem

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

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

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

【问题讨论】:

  • 分享你工作/尝试的代码。!让我们到目前为止做了什么。这不是在 Stackoverflow 上提问的正确方式。
  • @NestorLeCastor 请添加您的部分html代码伙伴...以便我们更好地指导您...
  • 请写下你的 Html 和 Css 代码,我会建议你回答。
  • 您可以将input 稍微加宽,以便在第四个字符之后留出克拉空间:jsfiddle.net/n23dfs4t/1

标签: javascript html css input scroll


【解决方案1】:

我看到了 2 个解决方案:

CSS 解决方案

就像评论中所说,您可以稍微增加输入的 with 以防止这种“跳跃”行为 喜欢:width : 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

【讨论】:

    【解决方案2】:

    我在你的 CSS 代码中对你的字段宽度做了一些小改动,见下文:

    input {
    width: 205px;
    height: 50px;
    font-size: 30px;
    font-family: "Courier", monospace;
    letter-spacing: 28px;
    text-indent: 18px;
    position: fixed;
    padding: 0;
    margin: 0;
    white-space: nowrap;
    overflow: hidden;
    

    }

    现在尝试输入一些内容,并留意第四个字符。

    希望这会有所帮助。

    索海尔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多