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

浏览器兼容性

另见