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月.
语法
js
addRange(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> |
浏览器兼容性
参见
- 此方法所属的接口:
Selection