大网数据广告活动
Web 标准与前端开发

EditContext: updateText() method

· 52CE 我爱测

The **`updateText()`** method of the EditContext interface updates the internal text content of an `EditContext` object.

EditContext API

The updateText() method of the EditContext interface updates the internal text content of an EditContext object.

This method doesn't need to be used when the user types text in the associated element. The EditContext object will automatically update its internal text content, and will fire EditContext.textupdate_event events as needed.

This method can, however, be used when the user interacts with the text content in other ways, such as when pasting text from the clipboard.

Syntax

updateText(rangeStart, rangeEnd, text)

Parameters

  • rangeStart
    • : A number representing the start of the range of text to replace.
  • rangeEnd
    • : A number representing the end of the range of text to replace.
  • text
    • : A string representing the new text content.

Return value

None (undefined).

Exceptions

  • TypeError
    • : Thrown if the method is called with less than three arguments.

Examples

Updating the editor when the user pastes text in it

This example shows how to use the updateText method to update the text content in the EditContext of a <canvas> element when the user presses the <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>V</kbd> shortcut to paste some text.

The example also uses the Clipboard.readText() method to read the text from the clipboard.

<canvas id="editor-canvas"></canvas>
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");

const editContext = new EditContext();
canvas.editContext = editContext;

function render() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillText(editContext.text, 0, 40);
}

editContext.addEventListener("textupdate", (e) => {
  render();
});

canvas.addEventListener("keydown", async (e) => {
  if (e.key === "v" && (e.ctrlKey || e.metaKey)) {
    const pastedText = await navigator.clipboard.readText();
    console.log(
      `The user pasted the text: ${pastedText}. Updating the EditContext text.`,
    );

    editContext.updateText(
      editContext.selectionStart,
      editContext.selectionEnd,
      pastedText,
    );

    editContext.updateSelection(
      editContext.selectionStart + pastedText.length,
      editContext.selectionStart + pastedText.length,
    );

    render();
  }
});

Specifications

Browser compatibility

See also

  • The EditContext interface it belongs to.

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。