Range: compareBoundaryPoints() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Range 介面的 compareBoundaryPoints() 方法將該 Range 的邊界點與另一個 Range 的邊界點進行比較。

語法

js
compareBoundaryPoints(how, otherRange)

引數

how

描述比較方法的常量

  • Range.END_TO_END 將此 Range 的結束邊界點與 otherRange 的結束邊界點進行比較。
  • Range.END_TO_START 將此 Range 的起始邊界點與 otherRange 的結束邊界點進行比較。
  • Range.START_TO_END 將此 Range 的結束邊界點與 otherRange 的起始邊界點進行比較。
  • Range.START_TO_START 將此 Range 的起始邊界點與 otherRange 的起始邊界點進行比較。
otherRange

一個用於與此 Range 比較邊界點的 Range 物件。

返回值

一個數字。

  • 如果此 Range 的指定邊界點在 otherRange 的指定邊界點之前,則返回 -1
  • 如果此 Range 的指定邊界點與 otherRange 的指定邊界點相同,則返回 0
  • 如果此 Range 的指定邊界點在 otherRange 的指定邊界點之後,則返回 1

此 API 與通用約定一致:當比較 A 到 B 時,負數表示 A 在 B 之前,反之亦然(例如,參見 Array.prototype.sort())。Range 的比較方向是 thisother,與 String.prototype.localeCompare() 相同。然而,對於 how 引數,邊界點的指定順序是相反的:END_TO_START 比較的是 this起始點和 other結束點。

異常

NotSupportedError DOMException

如果 how 引數的值無效,則丟擲此異常。

示例

下面,我們在同一個文字節點上建立兩個 Range,並比較它們不同的邊界點。

js
const text = new Text("0123456789");

const thisRange = new Range();
thisRange.setStart(text, 1);
thisRange.setEnd(text, 6);

const otherRange = new Range();
otherRange.setStart(text, 1);
otherRange.setEnd(text, 4);

// The ranges look like this:
// thisRange start   v---------v thisRange end
//                  0 1 2 3 4 5 6 7 8 9
// otherRange start  ^-----^ otherRange end

// this start is *same as* other start
thisRange.compareBoundaryPoints(Range.START_TO_START, otherRange); // 0

// this end is *after* other start
thisRange.compareBoundaryPoints(Range.START_TO_END, otherRange); // 1

// this start is *after* other end
thisRange.compareBoundaryPoints(Range.END_TO_START, otherRange); // -1

// this end is *after* other end
thisRange.compareBoundaryPoints(Range.END_TO_END, otherRange); // 1

規範

規範
DOM
# dom-range-compareboundarypoints

瀏覽器相容性

另見