SoFunction
Updated on 2025-04-13

Analysis of the difficulty of creating your own HTML online editor

What is an HTML online editor actually

In fact, there are several implementation methods, and the most used and most compatible one is the iframe method.

<iframe src="" frameborder="0"></iframe>

It is not possible to use this empty iframe alone, and you also need to use Javascript to set it to editable:

= "on";
= true;

In other words,HTML online editor is an editable iframe

How to achieve functions such as bold, italic, underline, and linking

The browser has provided an interface to implement these functionsexecCommand

(cmd, isDefaultShowUI, value);

The meaning of these three parameters is:

  • cmd: There are a lot of command text, IE can readhere, Firefox can be viewedhere
  • isDefaultShowUI: Whether to display the interactive interface by default, such as when linking, you can fill in the link through the interface. However, there is a compatibility problem with this parameter. Generally, it is set to false to disable it and an interactive interface is created.
  • value: The value passed in, some commands can be omitted.

The problem with execCommand is that the generated code may not be standard. For example, under IE, text bolding is used instead of strong tags.

Interaction issues

It is impossible for users to always enter the editor, such as bolding, inserting pictures and other functions are operated through buttons. Suppose the user wants to bold a selected text, and when he presses the bold button, the selection and focus will follow, so the selection (selected text) is lost, and the operation cannot be completed; similarly, the insertion position will also be lost when inserting the picture.

That is, save the selection that last appears in the editor. The solution I took is to use a timer (setInterval) when the focus is in the editorGet the current selection regularly. Constituency programming is rarely used, and there are many compatibility issues when done, mainly refer to Microsoft.MSDNTextRange ControlRange) and Mozilla'sMDCRange Selection)

Carriage Entry Problem

Under IE, press Enter to change the paragraph to generate <p>, but under Firefox it is a line to change, and what is generated is <br>. To solve this problem, you must listen to the keydown event. If you detect that the key is pressed, insert "<p></p>".

Get the standard code

How to get edited content? This question is very simple, just get the innerHTML in the iframe page body:

var content = ;

However, innerHTML under IE is very unstandard: the tag name is capitalized, the attribute is wrapped without quotes, and a single tag does not have an ending character... Even the code obtained under Firefox has a small number of flaws. You need to use it at this timeRegular expressionsStandardize the code.

Summarize

Not to mention it, do the HTML editor and you will knowCKEditorHow powerful it is.