Demo: https://ma125120.github.io/ma-dom/test/exec.html (only for reference, to realize the function of the basis of the rich text editor, such as there is need to improve, can expand or in the comments below, your precious opinions).

A few days ago, I needed to use a rich text editor in the project. I looked at the popular rich text editor on Github, but the volume was too large. Due to the limited bandwidth of the company server, I had to implement a simple rich text editor by myself.

The method focuses on document.execCommand and html5’s global properties for contenteditable (Document. designMode also works, but I think it’s better for contenteditable, Look at the rich text editors on Github, which are mostly div elements with contenteditable attributes).

  1. The document.execCommand method operates on selected text in a document. What elements are considered valid selected text?
  2. For HTML documents, switch to designMode or use elements with the contentEditable property. Input fields and Textarea are also available, but there are many restrictions on using document.execCommand for these text fields. After all, the value of a text box can only be a string, so many formatting methods for text are not worth it.
  3. When the text is selected, the text can be formatted by simply calling the document.execCommand method and passing in the corresponding parameters. The specific supported operations can be accessed by going to the MDN or the link above. Note: When used in Firefox, the second argument must be false, otherwise this function will fail.
  4. One more thing to note:Once the text is selected, the binding element that triggers the document.execCommand method should ideally be a button or img elementFinally, do not use other elements such as div, because clicking on an element such as div will change the selected area of the document to the element you clicked onDistrict lostThe problem. Although it can be used on elementsuser-select: none;Property to avoid selection loss, but this method has browser compatibility issues, such as sogou browser does not support.

The Demo uses event listening to listen on elements with exec classes. When clicked on the element, the values of the data-exec and data-exec2 properties of the element are used as the first and third parameters of the Document. execCommand method. Thus the realization of text formatting. For practical use in a project, it’s easy to just use my event listener and add a div element with a contenteditable attribute, a button with a data-exec attribute and an exec class to the document.

Github address: github.com/ma125120/ma… (Demo only realizes the basic function of rich text editor, if you need to improve, you can expand or comment below, put forward your valuable opinions).