1. 開発者向けのウェブ技術
  2. Web API
  3. TextUpdateEvent
  4. TextUpdateEvent: selectionStart プロパティ

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

TextUpdateEvent: selectionStart プロパティ

利用可能性は限定的

この機能はベースラインではありません。最も広く使用されているブラウザーの一部で動作しません。

Want more support for this feature? Tell us why.

Experimental: これは実験的な機能です。
本番で使用する前にブラウザー互換性一覧表をチェックしてください。

読み取り専用プロパティ TextUpdateEvent.selectionStart は、EditContext のオブジェクトに関連付けられた編集可能な領域のテキストコンテンツ内の選択範囲 (またはキャレット) の始点の位置を表します。

Number です。

textupdate を用いて編集されたテキストとユーザーの選択を描画する

この例では、selectionStart プロパティを用いて textupdate イベントハンドラー内で選択されたテキストを描画する方法を示します。

css
#editor {
 height: 200px;
 background: #eee;
 color: black;
}
.selection {
 display: inline-block;
 vertical-align: bottom;
 background: blue;
 color: white;
 min-width: 2px;
 height: 3ex;
}
html
<div id="editor"></div>
js
const editorEl = document.getElementById("editor");
const editContext = new EditContext();
editorEl.editContext = editContext;
editContext.addEventListener("textupdate", (e) => {
 // 現在のコンテンツをクリアします。
 editorEl.textContent = "";
 const text = editContext.text;
 const { selectionStart, selectionEnd } = e;
 // 選択範囲の前のテキストを描画します。
 const textBefore = document.createElement("span");
 textBefore.textContent = text.substring(0, selectionStart);
 // 選択されたテキストまたはキャレットを描画します。
 const textSelected = document.createElement("span");
 textSelected.classList.add("selection");
 textSelected.textContent = text.substring(selectionStart, selectionEnd);
 // 選択範囲の後のテキストを描画します。
 const textAfter = document.createElement("span");
 textAfter.textContent = text.substring(selectionEnd);
 editorEl.appendChild(textBefore);
 editorEl.appendChild(textSelected);
 editorEl.appendChild(textAfter);
 console.log(`Text before selection: ${textBefore.textContent}`);
 console.log(`Selected text: ${textSelected.textContent}`);
 console.log(`Text after selection: ${textAfter.textContent}`);
});

仕様書

仕様書
EditContext API
# dom-textupdateevent-selectionstart

ブラウザーの互換性

MDN の改良に協力

協力方法を知る

このページは MDN の貢献者によって に最終更新されました。

AltStyle によって変換されたページ (->オリジナル) /