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介面。