Selection: addRange() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Selection.addRange() 方法将一个 Range 对象添加到 Selection 对象中。

语法

js
addRange(range)

参数

range

将要添加到 Selection 中的 Range 对象。

返回值

无(undefined)。

示例

注意: 目前只有 Firefox 支持多个选区范围,如果选择区域已包含一个范围,其他浏览器将不会添加新的范围。

HTML

html
<p>
  I <strong>insist</strong> that you <strong>try</strong> selecting the
  <strong>strong words</strong>.
</p>
<button>Select strong words</button>

JavaScript

js
let button = document.querySelector("button");

button.addEventListener("click", () => {
  const selection = window.getSelection();
  const strongElems = document.getElementsByTagName("strong");

  if (selection.rangeCount > 0) {
    selection.removeAllRanges();
  }

  for (const node of strongElems) {
    const range = document.createRange();
    range.selectNode(node);
    selection.addRange(range);
  }
});

结果

规范

规范
Selection API
# dom-selection-addrange

浏览器兼容性

另见