Range: compareBoundaryPoints() 方法
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 的比較方向是 this 到 other,與 String.prototype.localeCompare() 相同。然而,對於 how 引數,邊界點的指定順序是相反的:END_TO_START 比較的是 this 的起始點和 other 的結束點。
異常
NotSupportedErrorDOMException-
如果
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 |
瀏覽器相容性
載入中…