Selection:setBaseAndExtent() 方法

Baseline 已廣泛支援

該特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 2017 年 4 月以來,它已在各大瀏覽器上可用。

Selection 介面的 setBaseAndExtent() 方法設定選區為一個範圍,該範圍包含兩個指定 DOM 節點的所有部分或部分內容,以及它們之間的任何內容。

錨點和焦點節點可以位於 Shadow tree 中,如果瀏覽器支援的話。

語法

js
setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset)

引數

anchorNode

選區開始處的節點。

anchorOffset

從錨點節點開始需要排除的子節點數量。因此,例如,如果值為 0,則包含整個節點。如果值為 1,則包含整個節點減去第一個子節點。依此類推。

如果 anchorNode 是一個 Text 節點,則偏移量指的是從 Node.textContent 開始需要從選區中排除的字元數。

focusNode

選區結束處的節點。

focusOffset

從焦點節點開始需要包含在選區中的子節點數量。因此,例如,如果值為 0,則整個節點被排除。如果值為 1,則包含第一個子節點。依此類推。

如果 focusNode 是一個 Text 節點,則偏移量指的是從 Node.textContent 開始需要包含在選區中的字元數。

注意: 如果焦點位置在文件中出現在錨點位置之前,則選區的方向會反轉——游標會放置在文字的開頭而不是結尾,這對任何後續的鍵盤命令都很重要。例如,Shift + ➡︎ 會導致選區從開頭收窄而不是在結尾增長。

返回值

無(undefined)。

異常

IndexSizeError DOMException

如果 anchorOffset 大於 anchorNode 中的子節點數量,或者 focusOffset 大於 focusNode 中的子節點數量,則會丟擲此錯誤。

示例

在此示例中,我們有兩個段落,其中包含 span 元素,每個 span 包含一個單詞。第一個被設定為 anchorNode,第二個被設定為 focusNode。我們還有一個額外的段落位於這兩個節點之間。

接下來,我們有兩個表單輸入框,允許您設定 anchorOffsetfocusOffset — 它們都具有預設值 0。

我們還有一個按鈕,按下時會呼叫一個函式,該函式使用指定的偏移量執行 setBaseAndExtent() 方法,並將選區複製到 HTML 最底部的輸出段落中。

html
<h1>setBaseAndExtent example</h1>
<div>
  <p class="one">
    <span>Fish</span><span>Dog</span><span>Cat</span><span>Bird</span>
  </p>
  <p>MIDDLE</p>
  <p class="two">
    <span>Car</span><span>Bike</span><span>Boat</span><span>Plane</span>
  </p>
</div>

<div>
  <p>
    <label for="aOffset">Anchor offset</label>
    <input id="aOffset" name="aOffset" type="number" value="0" />
  </p>
  <p>
    <label for="fOffset">Focus offset</label>
    <input id="fOffset" name="fOffset" type="number" value="0" />
  </p>
  <p><button>Capture selection</button></p>
</div>

<p><strong>Output</strong>: <span class="output"></span></p>

注意: <p class="one"><p class="two"> 的開始標籤及其後面的 <span> 開始標籤之間故意沒有 空格 — 以避免出現會影響預期子節點數量的文字節點。(即使這些文字節點只包含空格,它們仍然是額外的子節點;更多資訊請參閱 Node.firstChild 示例)。

JavaScript 程式碼如下:

js
const one = document.querySelector(".one");
const two = document.querySelector(".two");

const aOffset = document.getElementById("aOffset");
const fOffset = document.getElementById("fOffset");

const button = document.querySelector("button");

const output = document.querySelector(".output");

let selection;

button.onclick = () => {
  try {
    selection = document.getSelection();
    selection.setBaseAndExtent(one, aOffset.value, two, fOffset.value);
    const text = selection.toString();
    output.textContent = text;
  } catch (e) {
    output.textContent = e.message;
  }
};

請嘗試下面的即時示例,設定不同的偏移量值,看看它們如何影響選區。

注意: 您可以在 GitHub 上找到此示例也可以線上檢視)。

規範

規範
Selection API
# dom-selection-setbaseandextent

瀏覽器相容性

另見