【问题标题】:select editable text on focus with execCommand使用 execCommand 选择焦点上的可编辑文本
【发布时间】:2018-03-24 21:40:24
【问题描述】:

我有一个简单的代码,假设选择焦点元素的所有内容:

html:

  <div tabindex="-1" class="data" contenteditable="true"  (focusin)="focusin($event)" (focusout)="focusout($event)"  >Content</div>

.ts:

focusin(e) {
  console.log("focusin");
  document.execCommand("selectall");
}

问题在于这段代码选择了文档中的所有文本,而不仅仅是关注的文本。从我在网上看到的情况来看,如果一个元素被关注,这不是全选应该如何工作的:

How to select all text in contenteditable div?

有解决办法吗?

【问题讨论】:

    标签: angular textselection execcommand


    【解决方案1】:

    这是适用于 Chrome 和最新浏览器版本的解决方案:

    focusin(e) {
      var range = document.createRange();
      range.selectNodeContents(e.target);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    }
    
    猜你喜欢
    • 2011-09-22
    • 2011-09-01
    • 2013-02-06
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多