Angular 5 +如何使用IE 11中的键盘向左/向右选项逐个字符移动光标

时间:2019-05-08 13:15:09

标签: javascript angular cursor internet-explorer-11 ag-grid

我正在将Angular 5与Ag-Grid Enterprise Addition一起使用。我正在使用IE11浏览器。不幸的是,在网格中,使用键盘的左/右选项,光标卡住了并且无法移至输入框中的下一个字符。因此,我想到了将光标显式移动到下一个字符。我正在为此使用Javascript范围。我在此行document.getSelection()。addRange(range)遇到错误。请找到以下自定义NumericComponent的代码,输入框的屏幕截图和错误。我不确定这是否是正确的方法。谁能指导我如何解决此问题?

<input #input  id="numericinput" style="width: 100%; height: 100%;" (keydown)="onKeyDown($event)" [(ngModel)]="value" (dblclick) = "$event.target.select()">
              <button (click)="clear()" style="position:absolute;top:5px;right:2px;cursor:pointer;color:grey;background-color:white;border:none;">
                <span>&#10060;</span>
              </button>

onKeyDown(event): void {
        var key = event.which || event.keyCode;
        if(key === 37 || key === 39){
          let error ;
          event.stopPropagation();                      
          let inputDocument = document.getElementById('numericinput');    
          let range = document.createRange();
          range.collapse(true);        
          range.setEnd(inputDocument.firstChild, 0);          
          range.setStart(inputDocument.firstChild, this.input.element.nativeElement.value.length);          
          document.getSelection().removeAllRanges;          
          document.getSelection().addRange(range);                          
        }
        if (!this.isKeyPressedNumeric(event)) {
            if (event.preventDefault) event.preventDefault();
        }

    }

enter image description here

1 个答案:

答案 0 :(得分:0)

下面是我完成任务的解决方案

var key = event.which || event.keyCode;
        var iCaretPos = 0;
        if(key === 37 || key === 39){   
            //Left or right       
          let inputDocument = document.getElementById('numericinput');
          const element : HTMLInputElement = <HTMLInputElement>inputDocument;
          event.stopPropagation();                                                  
          let selectionStart = 0;          
          if(key === 39 && this.iCaretPos < element.innerHTML.length+1){               
                selectionStart = this.iCaretPos;
                this.iCaretPos = this.iCaretPos +1;
          }else if(key === 37 && this.iCaretPos !== 0){               
                selectionStart = this.iCaretPos;
                this.iCaretPos = this.iCaretPos -1;
          }  
          let selectionEnd = this.iCaretPos;          
            if (element.setSelectionRange) {                                          
                element.focus();
                element.setSelectionRange(selectionStart, selectionEnd);
            }        
        }