EditContext: updateSelection() 方法
EditContext 接口的 updateSelection() 方法会更新可编辑文本上下文中选区(selection)的内部状态。当用户通过点击或拖动鼠标,或使用键盘等方式与 EditContext 的关联元素中的文本渲染进行交互时,就会使用此方法来更新选区状态。
语法
js
updateSelection(start, end)
参数
返回值
无 (undefined)。
异常
TypeError-
如果调用方法时提供的参数少于两个,或者任一参数不是非负数,则会抛出此错误。
示例
用户与文本交互时更新选区
此示例展示了如何在用户使用箭头键在可编辑区域移动插入符号或选择文本时,使用 updateSelection 方法更新 canvas 元素的 EditContext 中的选区。
html
<canvas id="editor-canvas"></canvas>
js
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;
canvas.addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") {
const newPosition = Math.max(editContext.selectionStart - 1, 0);
if (e.shiftKey) {
editContext.updateSelection(newPosition, editContext.selectionEnd);
} else {
editContext.updateSelection(newPosition, newPosition);
}
} else if (e.key === "ArrowRight") {
const newPosition = Math.min(
editContext.selectionEnd + 1,
editContext.text.length,
);
if (e.shiftKey) {
editContext.updateSelection(editContext.selectionStart, newPosition);
} else {
editContext.updateSelection(newPosition, newPosition);
}
}
console.log(
`The new EditContext selection is ${editContext.selectionStart}, ${editContext.selectionEnd}`,
);
});
规范
| 规范 |
|---|
| EditContext API # dom-editcontext-updateselection |
浏览器兼容性
加载中…
另见
- 它所属的
EditContext接口。