Changing the keypress

后端 未结 6 1150
北荒
北荒 2020-11-27 06:16

In an input box or contenteditable=true div, how can I modify a keypress for the letter \"a\" to return a keybress for the letter \"b\"? I.e., every time you type the letter

6条回答
  •  感情败类
    2020-11-27 06:37

    Here is an example without using any libraries

    const input = document.querySelector('input')
    
    // this is the order of events into an input
    input.addEventListener('focus', onFocus)
    input.addEventListener('keydown', keyDown)
    input.addEventListener('keypress', keyPress)
    input.addEventListener('input', onInput)
    input.addEventListener('keyup', keyUp)
    input.addEventListener('change', onChange)
    input.addEventListener('blur', onBlur)
    
    function onFocus  (event) { info(event) }
    function keyDown  (event) { info(event) }
    function keyPress (event) {
      info(event)
      // this 2 calls will stop `input` and `change` events
      event.preventDefault();
      event.stopPropagation();
      
      // get current props
      const target = event.target
      const start = target.selectionStart;
      const end = target.selectionEnd;
      const val = target.value;
      
      // get some char based on event
      const char = getChar(event);
      
      // create new value
      const value = val.slice(0, start) + char + val.slice(end);
      
      // first attemp to set value
      // (doesn't work in react because value setter is overrided)
      // target.value = value
    
      // second attemp to set value, get native setter
      const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
        window.HTMLInputElement.prototype,
        "value"
      ).set;
      nativeInputValueSetter.call(target, value);
    
      // change cursor position
      target.selectionStart = target.selectionEnd = start + 1;
      
      // dispatch `input` again
      const newEvent = new InputEvent('input', {
        bubbles: true,
        inputType: 'insertText',
        data: char
      })
      event.target.dispatchEvent(newEvent);
    }
    function keyUp    (event) { info(event) }
    function onInput  (event) { info(event) }
    function onChange (event) { info(event) }
    function onBlur   (event) {
      // dispatch `change` again
      const newEvent = new Event('change', { bubbles: true })
      event.target.dispatchEvent(newEvent);
      info(event)
    }
    
    function info     (event) { console.log(event.type) }
    
    function getChar(event) {
      // will show X if letter, will show Y if Digit, otherwise Z
      return event.code.startsWith('Key')
        ? 'X'
        : event.code.startsWith('Digit')
          ? 'Y'
          : 'Z'
    }

提交回复
热议问题