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 |
瀏覽器相容性
載入中…