Skip to content

Commit

Permalink
[zh-cn]: update the translation of Range Range() constructor (mdn#2…
Browse files Browse the repository at this point in the history
  • Loading branch information
T34-active authored Nov 29, 2024
1 parent 69614e8 commit 2394ff1
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions files/zh-cn/web/api/range/range/index.md
Original file line number Diff line number Diff line change
@@ -1,55 +1,61 @@
---
title: Range()
title: Range:Range() 构造函数
slug: Web/API/Range/Range
l10n:
sourceCommit: c58e8c1dd6ecbcb63894c7dd17fb9495b9511b4e
---

{{ APIRef("DOM") }}{{seeCompatTable}}
{{ APIRef("DOM") }}

构造函数 **`Range()`** 返回一个新创建的 {{domxref("Range")}} 对象,新创建的对象属于全局 {{domxref("Document")}} 对象。
**`Range()`** 构造函数返回一个新创建的 {{domxref("Range")}} 对象,其起始点和结束点是全局 {{domxref("Document")}} 对象。

## 语法

```js-nolint
new Range()
```

### 参数

无。

## 示例

在下面的例子中,我们通过构造函数`Range()`创建了一个新的 range,并且使用{{domxref("Range.setStartBefore()")}} 和{{domxref("Range.setEndAfter()")}} 分别设置了起始位置。然后,通过方法{{domxref("window.getSelection()")}}{{domxref("Selection.addRange()")}}选中了选区 range
在这个示例中,我们使用 `Range()` 构造函数创建一个新的范围,并通过 {{domxref("Range.setStartBefore()")}} 和 {{domxref("Range.setEndAfter()")}} 方法设置其起始和结束位置。然后我们使用 {{domxref("window.getSelection()")}}{{domxref("Selection.addRange()")}} 方法选择该范围

### HTML

```html
<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
<p>Fourth paragraph.</p>
<p>第一段。</p>
<p>第二段。</p>
<p>第三段。</p>
<p>第四段。</p>
```

### JavaScript

```js
const paragraphs = document.querySelectorAll("p");

// 创建 Range 对象
// 创建新的范围
const range = new Range();

// Range 起始位置在段落 2
// 从第二个段落开始设置范围
range.setStartBefore(paragraphs[1]);

// Range 结束位置在段落 3
// 将范围结束于第三个段落
range.setEndAfter(paragraphs[2]);

// 获取 selection 对象
// 获取窗口的选择范围
const selection = window.getSelection();

// 添加光标选择的范围
// 将范围添加到窗口的选择范围中
selection.addRange(range);
```

### 结果

{{EmbedLiveSample("示例")}}
{{EmbedLiveSample("示例", 400, 210)}}

## 规范

Expand All @@ -61,4 +67,5 @@ selection.addRange(range);

## 参见

- [The DOM interfaces index](/zh-CN/docs/DOM/DOM_Reference)
- [DOM 接口索引](/zh-CN/docs/Web/API/Document_Object_Model)
- {{domxref("Document.createRange()")}}

0 comments on commit 2394ff1

Please sign in to comment.