代码之家  ›  专栏  ›  技术社区  ›  Pipo

普通javascript:在输入时截取密钥并更改密钥值

  •  3
  • Pipo  · 技术社区  · 6 年前

    我想截取在一个输入中键入的键,并将它们更改为其他键。

    例如,我想模拟每次按键时键入1。

    我在想这样的事情:

               //this example does not work, it will trigger an endless loop
    
                Array.from(document.querySelectorAll('.onlyOne')).forEach(input =>
                                   input.addEventListener('keydown', (event) => {      
                                    event.preventDefault();
                                    event.srcElement.dispatchEvent(new KeyboardEvent('keydown', { 'key': 49 }));
    
                                });
                            }
                        );
    

    我不能只加一个白色 event.target.value += 1; 因为当输入中已经有文本,并且光标不在文本的末尾,或者用户已用鼠标选择了所有文本时,如果在输入的末尾添加文本,则不会自然地执行操作。

    你能帮我一下吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   baao    6 年前

    通过从引发相同事件的事件中调度事件,您将创建一个无限循环,该循环将导致 Range Error: Maximum call stack size exceeded.

    而不是事件,只需添加 1 到光标在每个键上的位置。

    Array.from(document.querySelectorAll('.onlyOne')).forEach(input =>
      input.addEventListener('keydown', (event) => {
        event.preventDefault();
        event.target.insertAtCaret('1');
    }));
    
    
    HTMLInputElement.prototype.insertAtCaret = function (text) {
      text = text || '';
      if (document.selection) {
        // IE
        this.focus();
        var sel = document.selection.createRange();
        sel.text = text;
      } else if (this.selectionStart || this.selectionStart === 0) {
        // Others
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;
        this.value = this.value.substring(0, startPos) +
          text +
          this.value.substring(endPos, this.value.length);
        this.selectionStart = startPos + text.length;
        this.selectionEnd = startPos + text.length;
      } else {
        this.value += text;
      }
    };
    <input class='onlyOne' value="foo">

    htmlinputeElement.prototype.insertAtcret取自以下答案: https://stackoverflow.com/a/19961519/3993662

    You can change that to a normal function if you don't want to extend the built in's prototype .