此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Selection:addRange() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

Selection.addRange() 方法会向选区(Selection)中添加一个范围(Range)。

语法

js
addRange(range)

参数

range

一个将被添加到 Selection 中的 Range 对象。

返回值

无(undefined)。

示例

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

HTML

html
<p>
  我<strong>坚持</strong>要你<strong>试着</strong>选择这些<strong>加粗的词语</strong>。
</p>
<button>选择加粗的词语</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);
  }
});

结果

规范

Specification
Selection API
# dom-selection-addrange

浏览器兼容性

参见