首页 > Web开发 > 详细

[Angular HTML] Implementing The Input Mask Cursor Navigation Functionality -- setSelectionRange

时间:2017-07-24 09:22:47      阅读:295      评论:0      收藏:0      [点我收藏+]
  @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.

[Angular HTML] Implementing The Input Mask Cursor Navigation Functionality -- setSelectionRange

原文:http://www.cnblogs.com/Answer1215/p/7226850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!