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

2024-03-04

我想在 HTML/JS 中创建自己的 RichText 编辑器,如下所示:

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

但根据 MDN 的说法,文档.exec命令现已弃用(https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand),那么如何进行呢?

预先感谢您的回答


经过实验后,我找到了一种继续使用普通 HTML/CSS/JS 的方法,这是我的 JSFiddle :

https://jsfiddle.net/y9qzejmf/1/ 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}>`);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐