【问题标题】:OnKeyDown or KeyPress, detect the location of the inserted characterOnKeyDown 或 KeyPress,检测插入字符的位置
【发布时间】:2018-02-01 16:55:00
【问题描述】:

我不知道这是否可能(看起来不可能),但我正在尝试找到一种方法来检测在 HTML 输入标记的 onKeyDown 或 onKeyPress 事件中,结果值将是什么.

使用这些事件很重要。我不能只使用onKeyUp,因为到那时输入已经改变了。我想首先防止它发生。我还尝试将按下的键字符附加到字符串的末尾,但这并没有考虑到您在输入字段的字符串开头键入字符的情况。

有什么想法吗?我已经看了一段时间,似乎不可能,但我想我会问。

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    这里我有 2 个版本,一个带有 jQ​​uery,另一个单独带有 JavaScript。

    $("#inputJQuery").on("keydown", function(ev){
    	console.log("jQuery value:", $(this).val()); // this is the value before the key is added
    	console.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be inserted
    	console.log("jQuery selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
    })
    
    document.querySelector("#inputVanilla").onkeydown = function(ev){
    	console.log("VANILLA value:", this.value); // this is the value before the key is added
    	console.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be inserted
    	console.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <input id="inputJQuery" type="text"/>
    <input id="inputVanilla" type="text"/>

    【讨论】:

    • 我之前没有提到这一点,因为我没有意识到这是相关的,但我输入的是“数字”类型。看起来这只适用于文本输入。你知道有什么办法吗?如果没有,我只需要切换到输入文本
    • 数字类型的输入是不可能的。 stackoverflow.com/a/21959157/6605322
    【解决方案2】:

    只需检查键盘上的value 的length。这也适用于删除字符。

    您还可以在返回false 的条件中对此进行检查,以防止用户输入超过一定数量的字符。请注意,您可能希望对照 backspace 和 delete 键(分别为 keyCodes 8 和 46)检查此项,以便一旦达到最大长度,您就可以删除密钥。

    var input = document.getElementById('input');
    input.onkeydown = function(e) {
      console.log(input.value.length);
      if (input.value.length == 10) {
        if (e.keyCode === 8 || e.keyCode === 46) {
          return true;
        } else {
          return false;
        }
      }
    }
    &lt;input id="input"&gt;

    希望这会有所帮助! :)

    【讨论】:

    • 感谢您的回复,但似乎检查 value.length 只是在应用新字符之前返回输入的长度。这并不能帮助我确定在字符串中添加键的位置。例如,假设有人输入数字 100。然后他们在前面添加 1(使文本框 1100。我需要在将新值设置为输入之前知道新值,以便我可以防止它。我不知道你的回答怎么可能。谢谢
    • 哦,我明白了——我的错。您可以随时检查input.value 本身,例如if (input.value == 1100) { return false; },尽管这只会在他们实际输入后检查。话虽如此,您确实不应该阻止他们键入任何内容,而是在提交表单(或处理逻辑)后验证输入。
    • 不确定我是否同意。如果您将输入类型设置为“数字”,则 chrome 会完全阻止输入任何非数字输入。我只是想扩展同样的想法。允许否定,只要它们在正确的位置,例如
    • 哦,是的,您当然可以在前端进行验证。尽管阻止实际输入是相当不寻常的,但我不确定实际上是否有可能阻止输入被抢先输入。就我个人而言,我会检查blur() 事件,然后在输入不被接受时添加内联错误消息。然后用户知道他们需要改变它。尽管如此,前端验证永远不够,您也应该始终在后端验证(不要忘记您可以在提交表单后操作数据)。
    • 是的,后端是一个 REST Api,所以我不认为请求甚至来自这个页面,或者“一个页面”,哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2012-12-01
    • 2013-08-23
    • 2016-04-21
    • 2018-03-15
    相关资源
    最近更新 更多