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

來源:互聯網
上載者:User

標籤:pre   character   nal   tab   turn   selection   list   class   handle   

  @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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.