Range:selectNodeContents() 方法
Range.selectNodeContents() 方法将 Range 设置为包含一个 Node 的内容。
开始和结束 Range 的父 Node 将是参考节点。startOffset 为 0,endOffset 为参考节点中包含的子 Node 或字符的数量。
语法
js
selectNodeContents(referenceNode)
参数
返回值
无(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 |
浏览器兼容性
加载中…