JavaScript リッチテキストエディターのクリアとリセット

JavaScript リッチテキストエディターのクリアとリセット

内容の消去、初期文書への復元、フォームのリセットを区別し、未保存の下書きを守ります。

クリアとリセットの違い

クリアは現在の文書を空の値に置き換えます。リセットは指定した初期文書を復元します。データベースのレコードやアップロード済み画像は削除しません。同じエディターを使い、innerHTML で DOM を置き換えないでください。

完全なサンプルを実行する

アプリからエディターのファイルを配信します。消去前に確認し、キャンセル時には編集内容を保持し、送信時には最新の HTML を読みます。通信は行いません。タイトルはネイティブのフォーム操作で戻り、文書は明示的に復元します。

<link rel="stylesheet" href="/richtexteditor/rte_theme_default.css">
<script src="/richtexteditor/rte.js"></script>
<script src="/richtexteditor/plugins/all_plugins.js"></script>
<style>body{font:16px/1.6 system-ui;max-width:960px;margin:24px auto;padding:0 16px}button,input{min-height:44px;box-sizing:border-box}button{padding:8px 16px} .actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:16px}</style>
<h1>Clear or reset a rich text editor</h1>
<form id="note-form">
  <label>Title <input name="title" value="Project notes"></label>
  <div style="max-width:100%;overflow-x:auto"><div id="editor"></div></div>
  <div class="actions">
    <button type="button" id="clear">Clear content</button>
    <button type="reset">Restore initial form</button>
    <button type="submit">Check HTML</button>
  </div>
  <p id="status" role="status" aria-live="polite"></p>
</form>
<script>
const initialHTML = "<h2>Project notes</h2><p>Keep <strong>this starting document</strong>.</p>";
const editor = new RichTextEditor("#editor", { toolbar: "full", height: "320px" });
const form = document.getElementById("note-form");
const status = document.getElementById("status");
editor.setHTMLCode(initialHTML);
document.getElementById("clear").addEventListener("click", () => {
  if (!window.confirm("Clear the current document? This demo has no saved backup.")) return;
  editor.setHTMLCode("");
  status.textContent = "Content cleared. Title unchanged. Nothing was saved.";
});
form.addEventListener("reset", event => {
  if (!window.confirm("Restore the initial title and document?")) {
    event.preventDefault();
    return;
  }
  // Native reset restores ordinary fields; explicitly restore the editor.
  editor.setHTMLCode(initialHTML);
  status.textContent = "Initial form restored. Nothing was saved.";
});
form.addEventListener("submit", event => {
  event.preventDefault();
  // Read live editor data, not the original markup or a stale hidden field.
  const html = editor.getHTMLCode();
  status.textContent = "Current HTML: " + html.length + " UTF-16 units. No request sent.";
});
window.resetDemo = { editor, initialHTML };
</script>

自動保存とリセットを調整する

自動保存はリセットを通常の編集とみなす場合があります。保存、一時停止、新規下書きのどれにするか決めます。サーバーが受理した書き込みをクライアントのリセットで取り消せません。保存を直列化し、バージョンを検証し、保存完了後にサーバー上の削除を通知します。この例に自動保存や保存データの削除はありません。

フォームへの組み込み前に確認する

両方の確認をキャンセルして、タイトルと文書が残ることを確認します。クリアでは文書だけを消去します。両方を編集して初期フォームに戻し、キーボード送信、長いタイトル、320px 画面も試します。プログラムによる置換が元に戻せると約束せず、必要なら復旧用下書きを別に保持します。

次に読む