zoukankan      html  css  js  c++  java
  • [Angular HTML] Implementing The Input Mask Cursor Navigation Functionality -- setSelectionRange

      @HostListener('keydown', ['$event', '$event.keyCode'])
      onKeyDown($event: KeyboardEvent, keyCode) {
    
        if(keyCode !== TAB) {
          $event.preventDefault();
        }
    
        // get value for the key
        const val = String.fromCharCode(keyCode);
        // get position
        const cursorPos = this.input.selectionStart;
    
        switch(keyCode) {
          case LEFT_ARROW:
            this.handleLeftArrow(cursorPos);
            return;
          case RIGHT_ARROW:
            this.handleRightArrow(cursorPos);
            return;
        }
    
        overWriteCharAtPosition(this.input, val, cursorPos);
        this.handleRightArrow(cursorPos);
      }
    
      handleRightArrow(cursorPos) {
        const valueBeforeCursor = this.input.value.slice(cursorPos + 1);
        const nextPos = findIndex(valueBeforeCursor, (char) => !includes(SPECIAL_CHARACTERS, char));
        if(nextPos > -1) {
          const newNextPos = cursorPos + nextPos + 1;
          this.input.setSelectionRange(newNextPos, newNextPos);
        }
      }
    
      handleLeftArrow(cursorPos) {
        const valueAfterCursor = this.input.value.slice(0, cursorPos);
        const previousPos = findLastIndex(valueAfterCursor, (char) => !includes(SPECIAL_CHARACTERS, char));
        if(previousPos > -1) {
          this.input.setSelectionRange(previousPos, previousPos);
        }
      }

    We can use 'setSelectionRange(start, end)' to set cursor postion, in which start postion = end position.

  • 相关阅读:
    发球
    Java学习笔记
    驼峰式命名法
    公式编辑测试
    Python3.5 在Ubuntu16.04上无法画图的解决方案
    Ubuntu16.04 安装flash player
    Spring切面通知执行的顺序(Advice Order)
    修改别人写的利用AOP实现日志监控的问题
    传感器系列之4.10 酒精传感器
    传感器系列之4.8光敏传感器
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7226850.html
Copyright © 2011-2022 走看看