如何在没有 document.execCommand 的情况下在 HTML/JS 中创建 RichText 编辑器?

问题描述

我想像这样在 HTML/JS 中创建我自己的 RichText 编辑器:

https://www.youtube.com/watch?v=cOeTHVlFDYs

但根据 MDN,document.execCommand 现在已被弃用 (https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand),那么如何进行?

提前感谢您的回答

解决方法

经过试验后,我找到了一种处理普通 HTML/CSS/JS 的方法,这是我的 JSFiddle:

https://jsfiddle.net/y9qzejmf/1/

function insertTag(tag_name) {

  let editor_textarea = document.getElementById("editor_textarea");

  let selection = null;

  if (editor_textarea.selectionStart == editor_textarea.selectionEnd)
    selection = editor_textarea.selectionStart;
  else
    selection = editor_textarea.value.slice(editor_textarea.selectionStart,editor_textarea.selectionEnd);

  switch (tag_name) {
    case "strong":
      tag_name = "strong";
      break;

    case "italic":
      tag_name = "i";
      break;

    case "underline":
      tag_name = "u";
      break;

    case "code":
      tag_name = "code-tag";
      break;

    default:
      tag_name = null;
      break;
  }

  if (tag_name != null)
    editor_textarea.setRangeText(`<${tag_name}>${selection}</${tag_name}>`);
}