select 使用 execCommand 可编辑焦点文本
select editable text on focus with execCommand
我有一个简单的代码,假设 select 聚焦元素的所有内容:
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");
}
问题是这段代码 select 是文档中的所有文本,而不仅仅是重点关注的那个。从我在网上看到的情况来看,这并不是 select 所有应该工作,如果一个元素被聚焦:
How to select all text in contenteditable div?
有解决办法吗?
这是适用于 Chrome 和最新浏览器版本的解决方案:
focusin(e) {
var range = document.createRange();
range.selectNodeContents(e.target);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
我有一个简单的代码,假设 select 聚焦元素的所有内容:
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");
}
问题是这段代码 select 是文档中的所有文本,而不仅仅是重点关注的那个。从我在网上看到的情况来看,这并不是 select 所有应该工作,如果一个元素被聚焦:
How to select all text in contenteditable div?
有解决办法吗?
这是适用于 Chrome 和最新浏览器版本的解决方案:
focusin(e) {
var range = document.createRange();
range.selectNodeContents(e.target);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}