【问题标题】:Placing cursor at end of the text in html table cell将光标放在html表格单元格中文本的末尾
【发布时间】:2018-06-26 04:53:08
【问题描述】:

想要在每个<td> 的文本末尾设置光标焦点

 <table #sampleTable>
     <th>name</th>
     <th>number</th>
     <tr>
         <td #name contenteditable="true">
             jack
         </td>
         <td #number contenteditable="true">
             5487
         </td>
     </tr>
 </table>

组件.ts

@ViewChild('name') colName;
 ...
 ngAfterViewInit(){
     setTimeout(() => {
         this.colName.nativeElement.focus() //setting focus at name column
     }, 1000);   
 }

但无法在文本末尾设置光标。任何人都可以在不使用 Jquery 的情况下以 angular 的方式帮助我。

【问题讨论】:

标签: javascript css html angular


【解决方案1】:

演示:https://stackblitz.com/edit/angular-svtdvv

将此答案合并到浏览器兼容性解决方案中: contenteditable, set caret at the end of the text (cross-browser)

  @ViewChild('name') colName;
  ngAfterViewInit() {
    this.placeCaretAtEnd(this.colName.nativeElement);
    this.colName.nativeElement.focus();

  }

  placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
      && typeof document.createRange != "undefined") {
      var range = document.createRange();
      range.selectNodeContents(el);
      range.collapse(false);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    } 
    else if (typeof (<any>document.body).createTextRange != "undefined")      {
      var textRange = (<any>document.body).createTextRange();
      textRange.moveToElementText(el);
      textRange.collapse(false);
      textRange.select();
    }
  }

【讨论】:

  • 我刚刚将(keydown)="keyDownEvent($event)" 添加到&lt;td&gt;。在 .ts 中,rightarrow 将插入符号放在下一个兄弟列的末尾。但是对于leftarrow,它将插入符号放在错误的位置event.key == "ArrowLeft" &amp;&amp; event.srcElement.previousElementSibling != null) this.placeCaretAtEnd(event.srcElement.previousElementSibling);这里出了什么问题。
猜你喜欢
  • 2011-12-08
  • 2022-06-15
  • 1970-01-01
  • 2013-07-20
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多