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.

  • 相关阅读:
    MySQL主从复制原理
    MySQL调优
    apache禁止php解析--安全
    apache禁止指定的user_agent访问
    python---日常练习
    字符、字节的概念和区别;编码概念
    Django模型初识
    git安装
    Django--Hello
    fillder---断言/打断点,更改提交数据
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7226850.html
Copyright © 2011-2022 走看看