首页 > 代码库 > [Angular HTML] Implementing The Input Mask Cursor Navigation Functionality -- setSelectionRange
[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.
[Angular HTML] Implementing The Input Mask Cursor Navigation Functionality -- setSelectionRange
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。