如何在没有 document.execCommand 的情况下在 HTML/JS 中创建 RichText 编辑器?
How to create a RichText Editor in HTML/JS without document.execCommand?
我想在 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}>`);
}
我想在 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}>`);
}