微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在没有 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}>`);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。