EditContext:textformatupdate 事件
當使用 輸入法編輯器 (IME) 視窗進行文字輸入時,會觸發 EditContext 介面的 textformatupdate 事件。
當 IME 決定需要以不同方式格式化正在輸入的文字的某些部分以指示輸入狀態時,會觸發此事件。
下面的截圖展示了一個在 Windows 的記事本應用中使用日文 IME 輸入文字的示例。文字以粗下劃線進行格式化,以表明它是從 IME 的建議之一中組成的。

作為 Web 開發者,您應該監聽 textformatupdate 事件,並相應地更新可編輯區域中顯示的文字格式。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("textformatupdate", (event) => { })
ontextformatupdate = (event) => { }
事件型別
一個 TextFormatUpdateEvent。繼承自 Event。
事件屬性
除了下面列出的屬性之外,父介面 Event 的屬性也可使用。
TextFormatUpdateEvent.getTextFormats-
返回 IME 視窗希望應用於該文字的文字格式列表。
示例
渲染 IME 輸入文字的格式
在下面的示例中,textformatupdate 事件用於更新可編輯區域中文字的格式。請注意,此示例中的事件監聽器回撥僅在使用 IME 視窗或其他平臺特定的編輯 UI 表面輸入文字時呼叫。
html
<canvas id="editor-canvas"></canvas>
js
const TEXT_X = 10;
const TEXT_Y = 10;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
editContext.addEventListener("textformatupdate", (e) => {
// Clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render the text.
ctx.fillText(editContext.text, TEXT_X, TEXT_Y);
// Get the text formats that the IME window wants to apply.
const formats = e.getTextFormats();
// Iterate over the text formats
for (const format of formats) {
const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format;
const underlineXStart = ctx.measureText(
editContext.text.substring(0, rangeStart),
).width;
const underlineXEnd = ctx.measureText(
editContext.text.substring(0, rangeEnd),
).width;
const underlineY = TEXT_Y + 3;
// For brevity, this example only draws a simple underline.
// You should use the underlineStyle and underlineThickness values to draw the underline.
ctx.beginPath();
ctx.moveTo(TEXT_X + underlineXStart, underlineY);
ctx.lineTo(TEXT_X + underlineXEnd, underlineY);
ctx.stroke();
}
});
規範
| 規範 |
|---|
| EditContext API # dom-editcontext-ontextformatupdate |
瀏覽器相容性
載入中…