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 |
浏览器兼容性
加载中…