# SelectionContext

> 基础库 3.16.0 开始支持，低版本需做[兼容处理](1003706)。

> 相关文档: [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html)

SelectionContext 实例，可通过 [SelectorQuery.context](/miniprogram/dev/api/wxml/NodesRef/NodesRef.context) 获取。

[SelectionContext](/miniprogram/dev/api/wxml/SelectionContext) 通过 `id` 跟一个 [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html) 组件绑定，可主动控制组件内部选区。

## 方法

### [SelectionContext.selectRange(number start, number end)](/miniprogram/dev/api/wxml/SelectionContext/SelectionContext.selectRange)

主动设置 [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html) 组件内部选区范围。偏移以组件内所有有效 [text](https://developers.weixin.qq.com/miniprogram/dev/component/text.html) 单元拼接后的字符串为准。

### [SelectionContext.setBaseAndExtent(string anchorNodeId, number anchorOffset, string focusNodeId, number focusOffset)](/miniprogram/dev/api/wxml/SelectionContext/SelectionContext.setBaseAndExtent)

主动设置 [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html) 组件内部选区的起点与终点。节点 id 与偏移可由 [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html) 组件 selectionchange 事件返回的 firstNodeId/firstOffset、lastNodeId/lastOffset 得到。

### [SelectionContext.removeSelection()](/miniprogram/dev/api/wxml/SelectionContext/SelectionContext.removeSelection)

清除 [selection](https://developers.weixin.qq.com/miniprogram/dev/component/selection.html) 组件内部当前选区。

## 示例代码

```html
<selection id="selection">
  <text user-select>abcdefg</text>
</selection>
```

```javascript
Page({
  onReady() {
    wx.createSelectorQuery().select('#selection').context(ctx => {
      this.selectionContext = ctx
    }).exec()
  },
  selectPart() {
    this.selectionContext.selectRange(1, 5)
  },
  clearSelection() {
    this.selectionContext.removeSelection()
  },
})
```
