← 中文资源

简体中文版本

Selection API 读取选中的文本

输入框用 selectionStart/selectionEnd 定位高亮区间并切片取值;页面任意选区经 Range 加 getSelection 读取,最后把光标停回末尾等待继续输入。

阅读英文原文

实现说明

Selection API 读取选中的文本可以归结为函数 inputSelection。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 守卫 selectionStart === selectionEnd 满足时靠提前的 return 短路流程。
  • 跑完文件,输出里会留下标记——input selection:、page selection:、caret at end:。

常见问题

「Selection API 读取选中的文本」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

签名一览:function inputSelection()

核心语句

if (selectionStart === selectionEnd) return null; // caret, not a range
return comment.value.slice(selectionStart, selectionEnd);

代码示例

// Two selection surfaces: text inside an input, text anywhere in the page.
const comment = document.createElement('textarea');
comment.value = 'The rate limit reset at noon';

// selectionStart / selectionEnd mark the highlighted span inside the input.
function inputSelection() {
  const { selectionStart, selectionEnd } = comment;
  if (selectionStart === selectionEnd) return null; // caret, not a range
  return comment.value.slice(selectionStart, selectionEnd);
}

comment.setSelectionRange(4, 14);
console.log('input selection:', inputSelection());

// Page-level selection works on non-editable content through a Range.
const article = document.createElement('article');
article.textContent = 'Deploy notes for the auth service';
const range = document.createRange();
range.selectNodeContents(article);
const selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
console.log('page selection:', selection.toString());

// Park the caret at the end so the next keystroke appends.
comment.setSelectionRange(comment.value.length, comment.value.length);
console.log('caret at end:', comment.selectionStart === comment.value.length);