Selection: addRange() 方法
语法
js
addRange(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 | 
浏览器兼容性
加载中…
另见
- Selection,该方法所属的接口