Range:selectNodeContents() 方法

Baseline 已广泛支持

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

Range.selectNodeContents() 方法将 Range 设置为包含一个 Node 的内容。

开始和结束 Range 的父 Node 将是参考节点。startOffset 为 0,endOffset 为参考节点中包含的子 Node 或字符的数量。

语法

js
selectNodeContents(referenceNode)

参数

referenceNode

将在 Range 中选择其内容的 Node

返回值

无(undefined)。

示例

js
const range = document.createRange();
const referenceNode = document.querySelector("div");
range.selectNodeContents(referenceNode);

实时示例

此示例允许用户通过按钮选择和取消选择一个段落。使用 Document.createRange()Range.selectNodeContents()Selection.addRange() 来选择内容。使用 Window.getSelection()Selection.removeAllRanges() 来取消选择它。

HTML

html
<p id="p">
  <strong>Use the buttons below</strong> to select or deselect the contents of
  this paragraph.
</p>
<button id="select-button">Select paragraph</button>
<button id="deselect-button">Deselect paragraph</button>

JavaScript

js
const p = document.getElementById("p");
const selectButton = document.getElementById("select-button");
const deselectButton = document.getElementById("deselect-button");

selectButton.addEventListener("click", (e) => {
  // Clear any current selection
  const selection = window.getSelection();
  selection.removeAllRanges();

  // Select paragraph
  const range = document.createRange();
  range.selectNodeContents(p);
  selection.addRange(range);
});

deselectButton.addEventListener("click", (e) => {
  const selection = window.getSelection();
  selection.removeAllRanges();
});

结果

规范

规范
DOM
# dom-range-selectnodecontents

浏览器兼容性

另见