Keycode is always zero in Chrome for Android

后端 未结 10 2096
栀梦
栀梦 2020-12-05 13:17

I need to detect the keycode for a custom search box on my website, but the keycode always returns as zero on Chrome for Android (except for backspace, which returns 8). Has

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 13:33

    So in most Android browser if u use keydown or keyup you wont be able to get the data from key or keyCode or which or code

    You can use event.data(Inserted data key) and event.inputType(backspace or del in mobile)

    In order to achieve the functionality you need you have to apply condition based on user agent for android mobile

    if (navigator.userAgent.match(/Android/i)) {
        node.addEventListener('input', handleInput, false);
      } else {
        node.addEventListener('keydown', handleKeyDown, false);
      }
    
    
      const handleKeyDown = event => {
        event.preventDefault();
        if (!event.key) {
          return false;
        }
        genericFunctionHandleThings(event.key, event.code === 'Backspace');
      };
    
     const handleInput = event => {
        event.preventDefault(); // Here event.preventDefault doesn't stop user from typing
        genericFunctionHandleThings(event.data, event.inputType === 'deleteContentBackward');
        node.value = storedOrProcessedValue;
      };
    

    Here I have used node.value = storedOrProcessedValue because if we want to make some restriction for user typing we need to process and re assign it to the input

    You can use this with Input type text,url,email,tel these I have tested rest I need to check

提交回复
热议问题