保存和恢复文本选择范围

原文:HTML DOM - Save and restore the text selection

// 保存选择范围
// 如果有选区,返回Range实例
const save = function() {
  const selection = window.getSelection();
  return selection.rangeCount === 0 ? null : selection.getRangeAt(0);
};

// 恢复selection
// `range`是一个 `Range` 对象
const restore = function(range) {
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
};