Simple implementation of rich text editor | project copy |

create by db on 2021-3-17 15:46:50

Recently revised in 2021-3-18 15:56:01

Idle time to have a tight mind, busy time to have leisure fun

directory

  • preface

  • The body of the

    • What a rich text editor is
    • The implementation principle of rich text editor
    • Implement a simple rich text editor
  • conclusion

preface

Returns the directory

As a programmer, I was immersed in the ocean of business every day, either writing bugs or fixing bugs. Finally, the project came online, there were new projects to review, old projects to iterate… Waterfall, Agile, devOps… The project cycle is getting faster, the hair is falling out faster…

Vue 3.0 was released; Vite 2.0 was released; Webpack 5 released… Technology is iterating so fast that you can’t even learn…

You don’t have time to review your own projects!

End of joke time, actually I wanted to write a project about the secondary encapsulation of rich text editor. Unfortunately, time has passed so long that many of the details have been forgotten, so simply implement a rich text editor.

The body of the

What a rich text editor is

Returns the directory

For those of you who don’t know what a rich text editor is, we’ve been using it ever since we got Internet access from the village.

From early BBS post, post messages to the email editor, blogs, generally have a release information interface, after the input text, you can set text format, font size, thickness, color, such as style, this is a common application of the rich text editor, the following figure (from wangEditor, very beautiful an open source editor) :

In general, ** Rich Text Editor (RTE) ** is a wySIWYG Text Editor that can be embedded in the browser. It provides editing capabilities similar to Office Word.

The implementation principle of rich text editor

Returns the directory

The principles of a rich text editor are not complicated. The essence of this is to embed HTML code in a page element, and this element can be used as a document input field to edit text and set text styles, such as font style, size, color, and so on.

We then take the entire HTML code or extract it into JSON data, save it in the background, pull it out of the background when needed, and render it in a rich text editor as it was before saving.

So how do you make your HTML editable?

We know that HTML and tags can be used to edit text, so what should we use? So that brings up these properties

  • contenteditable
  • HTMLElement.contentEditable
  • designMode
  • document.execCommand

Contenteditable element content is editable

Details for reference: contenteditable | MDN

Contenteditable is an enumerated property that indicates whether an element can be edited by the user. Property compatibility is good, compatible with all major browsers.

The contenteditable property has two values:

  • True: Specifies that the element is editable
  • False: Specifies that the element is not editable

usage

It’s easy to use, just fill in the labels you need. As follows:

<p contenteditable="true">This is a paragraph. It's editable. Try to modify the text.</p>
Copy the code

inheritable

What if it’s nested?

<div contenteditable="true">I am a Div1 and MY Contenteditable is true<div>I am Div2 and do not have the contenteditable property set</div>
</div>
Copy the code

You can see that even nested relationships have editable tags that do not have the contenteditable property. Why? In fact, this property is inherited, as long as the parent, then the child will inherit, so that the child can also be edited.

If the children do not want to edit, add contenteditable=”false” to the children

tips

Finally, in this particular case, span names and ages are technically uneditable, right?

<div contenteditable="true">
  <span contenteditable="false">Name:</span>Xiao Ming<br />
  <span contenteditable="false">Age:</span>Twenty years of age</div>
Copy the code

Then just edit from the top line, and you’ll see that even the words in the span for contenteditable= “false” have been deleted. Why is that?

This is because the internal text of a false tag cannot be edited, but the external editor can delete the entire tag. So avoid that layout.

HTMLElement. ContentEditable shows that elements are editable

Details may refer to: HTMLElement contentEditable | MDN

ContentEditable is an enumerated property that indicates whether an element is editable or not.

The contentEditable property has three values:

  • “True” indicates that the element is editable.
  • “False” indicates that the element is not editable.
  • “Inherit” indicates that the element inherits the editable state of its parent.

usage

It’s easy to use, just fill in the labels you need. As follows:

document.getElementById('editor').contentEditable = true
Copy the code

Document.designmode The entire Document is editable

Details may refer to: the Document designMode | MDN

Document.designMode is a global attribute with the following characteristics:

  • Specifies whether the entire page is editable. When the page is editable, any elements on the page that support the contentEditable property become editable.
  • Can only be edited in Js
  • This property has two values —-on(this document is editable) |off(Default value. This document is not editable.)

DesignMode usage

DesignMode usage is also simple.

  1. Make the entire page editable:F12Open your console, type in a command, and you’ll see that the entire page is editable.
document.designMode = 'on'
Copy the code
  1. To make a<iframe> The document is editable:
iframeNode.contentDocument.designMode = 'on'
Copy the code

tips

According to the specification, this property defaults to “off”. Firefox follows this standard. Earlier versions of Chrome and Internet Explorer default to “inherit”. Starting with Chrome 43, the default value is “off” and “inherit” is no longer supported. In IE6 to IE10, the value is uppercase.

To set the entire document to designMode, you can set the designMode property on the document object itself. When the document is in design mode, the script will not run. It seems like a good idea to have a button inside the document to turn design mode on or off, but it doesn’t work.

When the user opens it, it will remain in design mode. The next time they click this button, it will be selected instead of clicked, and they click it again and will be able to edit its value. This is why it is best to set the designMode attribute for documents in the framework or IFrame if you want to use designMode.

Document. execCommand manipulates the elements of the editable content area

Details may refer to: the document execCommand | MDN

Now that the element is set up for contentedable, a basic rich text editor is already in place, but like the text input box, it’s just plain old. It would be perfect if it were easy to style content.

This uses the method of interacting with rich text styles — document.execcommand ()

This method takes three parameters:

  1. aCommandName
  • A DOMString, the name of the command. For a list of available commands, see Commands.
  1. aShowDefaultUI
  • A Boolean indicating whether the user needs to be prompted to provide a value for the command, usually false. Mozilla doesn’t implement it, so some browsers will get an error if they set the second parameter to true, but we usually set it to false for portability.
  1. aValueArgument
  • Indicates the parameter value for executing the current command. The default value is NULL.

usage

For example, to bold the selected text, the command expression would look like this:

document.execCommand(bold, false.null)
Copy the code

Easy to implement rich text editor

Returns the directory

Now that the principles are in place, let’s whip out our own rich text editor.

1. Set up the editor page

We need to create an HTML file. Let’s call it myeditor.html.

A simple rich text editor should have a series of style manipulation buttons and an edit box. Here I will simply implement five operation buttons, which are background color, font color, size +, size -, undo; Then simply change the style. The code is as follows:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>Doubao rich text editor</title>
  </head>
  <style type="text/css">
    #editor {
      width: 600px;
      height: 200px;
      border: 1px solid #ccc;
    }

    button {
      margin: 1px;
      border: 1px solid #aaa;
      background: #ffe;
      cursor: pointer;
      overflow: hidden;
    }

    button:hover {
      background: #ccc;
      border: 1px solid #00f;
    }
  </style>

  <body>
    <! Style action button -->
    <button id="btn1">The background color</button>
    <button id="btn2">The font color</button>
    <button id="btn3">The shop name +</button>
    <button id="btn4">Size -</button>
    <button id="btn5">undo</button>
    <! -- Edit box -->
    <div id="editor">Please enter...</div>
    <input id="printContent" type="button" value="Print editor content" />
  </body>
</html>
Copy the code

2. Achieve rich text editing function

Making the editor work only requires

  • Enable editing for elements editor.contentEditable = true;

  • Bind all style buttons with events that launch Document. execCommand.

  1. The first implementation of open element editingopenOrCloseEditorFunction:
/** ** function: enable element editing function * input: el: editor ID; Operate: Boolean, which indicates whether to enable or disable */
function openOrCloseEditor(el, operate) {
  var editor = document.getElementById(el)
  editor.contentEditable = operate
}
Copy the code
  1. Repopulate the button event binding functionbindBtnCommand:
// Button binding command
  function bindBtnCommand() {
    let btnConfigList = [{
      lab: 'backcolor'.value: '#f00'
    }, {
      lab: 'foreColor'.value: '#0f0'
    }, {
      lab: 'fontSize'.value: '+ 1'
    }, {
      lab: 'fontSize'.value: '1'
    }, {
      lab: 'undo'.value: '1'
    }]
    for (let i = 0; i < btnConfigList.length; i++) {
      document.getElementById("btn" + (i + 1)).onclick = function () {
        document.execCommand(btnConfigList[i].lab, false, btnConfigList[i].value); }}}}Copy the code
  1. Finally, bind each buttonclickBtnAnd then callinitEditorPut the editor into effect
<! <button id="btn1" onclick="clickBtn('backcolor','#f00')"> </button> <button id="btn2" <button id="btn3" onclick="clickBtn('fontSize',7)"> </button> <button id="btn4" onclick="clickBtn('fontSize',1)"> </button id="btn5" Onclick = "clickBtn (' undo ', 1)" > cancel < / button >Copy the code
  1. Next, implement the “print and edit content” button function:
// Get the editor embedded content
function getContent(el) {
  var editor = document.getElementById(el)
  return editor.innerHTML
}

// Prints button binding trigger events
document.getElementById('printContent').onclick = function (e) {
  var content = getContent('editor')
  document.write(content)
}
Copy the code
  1. Finally, the initialization function is calledinitEditorPut the editor into effect
// Initialize the editor
function initEditor() {
  openOrCloseEditor('editor'.'true') // Enable element editing
}
Copy the code

With that, our editor is complete, as follows:

conclusion

Returns the directory

It’s not really a project replay; It was so long ago that I couldn’t remember the details.

Project in hand, experience in mind. As long as they can gain something, incidentally also can help others, water point article what does it matter?

The road ahead is long, and I see no end.

Reference documentation

  • Implementation editor
  • DesignMode attributes of HTML | Jane books – ah, bean
  • Several mainstream use rich text editor (wysiwyg editor) commonly used to introduce | CSDN – Huang Zhiqian
  • Several mainstream useful introduction | CSDN – Huang Zhiqian markdown editor

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign

Complete code attached:

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>Doubao rich text editor</title>
</head>
<style type="text/css">
  #editor {
    width: 600px;
    height: 200px;
    border: 1px solid #ccc;
  }

  button {
    margin: 1px;
    border: 1px solid #aaa;
    background: #ffe;
    cursor: pointer;
    overflow: hidden;
  }

  button:hover {
    background: #ccc;
    border: 1px solid #00f;
  }
</style>

<body>
  <! Style action button -->
  <button id="btn1">The background color</button>
  <button id="btn2">The font color</button>
  <button id="btn3">The shop name +</button>
  <button id="btn4">Size -</button>
  <button id="btn5">undo</button>
  <! -- Edit box -->
  <div id="editor">Please enter...</div>
  <input id="printContent" type="button" value="Print editor content">
</body>
<script>
  initEditor();


  // Editor initializes the function
  function initEditor() {
    openOrCloseEditor('editor'.'true') // Enable element editing
    bindBtnCommand(); // Bind the command to the style button
  }

  /* * function: enable element editing function * input: el: editor ID; Operate: Boolean, which indicates whether to enable or disable */
  function openOrCloseEditor(el, operate) {
    var editor = document.getElementById(el);
    editor.contentEditable = operate;
  }

  // Button binding command
  function bindBtnCommand() {
    let btnConfigList = [{
      lab: 'backcolor'.value: '#f00'
    }, {
      lab: 'foreColor'.value: '#0f0'
    }, {
      lab: 'fontSize'.value: '+ 1'
    }, {
      lab: 'fontSize'.value: '1'
    }, {
      lab: 'undo'.value: '1'
    }]
    for (let i = 0; i < btnConfigList.length; i++) {
      document.getElementById("btn" + (i + 1)).onclick = function () {
        document.execCommand(btnConfigList[i].lab, false, btnConfigList[i].value); }}}// Get the editor embedded content
  function getContent(el) {
    var editor = document.getElementById(el);
    return editor.innerHTML;
  }

  // Prints button binding trigger events
  document.getElementById("printContent").onclick = function (e) {
    var content = getContent("editor");
    document.write(content);
  };
</script>

</html>
Copy the code

Postscript: Hello friends, if you think this article is good, remember to give a thumbs-up or star, your thumbs-up and star is my motivation to write more and richer articles!Making the address

Document agreement



dbThe document library 由 dbusingCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.

Based on thegithub.com/danygitgitOn the creation of works.

Use rights other than those authorized by this License agreement may be obtained from
Creativecommons.org/licenses/by…Obtained.

Copy the code