Basic implementation principle of online text editor

Source: Internet
Author: User

Reference Address: http://www.w3ctech.com/topic/140

Recently researched the principle of WYSIWYG text editor implemented in the browser, after understanding the basic principle and browsing the source of the relatively simple online editor of Zenpen, there is an enlightened feeling in this aspect.

Surprisingly, the browser that originally made it possible in the browser was IE5. In that era, IE is indeed a very advanced browser, now widely used AJAX technology, is not the first IE5 to provide it? But here is no longer discuss the original IE set of outdated API, and mainly to discuss HTML5 after the various browsers widely supported by a number of technical methods.

For WYSIWYG text editing, the need for a few basics is

    1. So that a certain portion of the DOM can be edited
    2. Can get and manipulate the area selected by the user
    3. Edit the part of the DOM can be modified at the same time, the implementation of such as adding styles and other functions

These features are very easy to implement.

Make DOM Editable

To make a portion of the HTML Dom into an edit state as a container, simply add a property to the Dom contentEditable . In general, it is div a article container that uses or elements as such.

The contentEditable child elements of the container element of the added property can be modified by the user, and if you want to nest a non-modifiable child element underneath the container, you need to explicitly add such a declaration to the child element contentEditable=‘false‘ .

Get and manipulate user selection

Operation and access to user selection is a very useful function, it can not only be used to implement the function of the editor presented here, but also can be used to implement the cursor position display prompt menu and other functions, in the subsequent changes in the editing section of the style modification is also commonly used.

It is very easy to get a Selection object:

var selection = window.getSelection();

The Selection object has anchorNode and focusNode two properties that can be used to get the start and end elements of the selected part, but not much practical (the general practical Range instead). It is also isCollapsed worth noting that when it is, the true selection area starts and ends at the same point, that is, the cursor blinks when no content is selected.

The Selection object also has many ways to modify the selection, mainly the editing of the Range object.

You can start by

var range = selection.getRangeAt(0);

To get the first chunk that is selected, and so on, you can also get the second and third one. For simplicity we only discuss the case where a block is selected. With the Range object in place, we can easily get the contents of the selected area. The Range object has a pair of properties that are used to get the start and end points of the selection area, respectively.

range.startContainer // 开始点所在的容器(元素)range.endOffset // 开始点在其容器内的偏移range.endContainer // 结束点所在的容器(元素)range.endOffset // 结束点在其容器内的偏移

In addition to these two pairs of properties, there is also a very useful property, that is

range.commonAncestorContainer // 选择范围的共同父元素

The above attribute is commonly used to detect the type/style of a selection, such as the detection of a public parent element of the selected range as an h1 element, then the button that represents h1 the element can be set to the active state in the toolbar.

It is important to note that the Range object returned is a class of mutable objects. Simply put, if a user's selection changes, the contents of the Range object will change. Therefore, to record the Range of a moment, you should record the two pairs of properties mentioned above. In addition, the properties of the Range object are read-only and need to be modified by the corresponding function method.

Range also defines a variety of functions to get content and modify content, detailed parameters and methods can be found in the documentation, here are a few common use case description.

Get the selected coordinate range

We can get the exact position of the cursor on the Web page, and we can also get a geometric representation of its rectangular border for the selection, which is convenient for us to display the prompt menu. Get the position of the cursor or the rectangular border of the selection to use

var rect = range.getBoundingClientRect();

rectThe properties included in the object include the rectangle's,,, and top left right bottom coordinates. If selected collapsed , these four properties can be used to calculate the position of the cursor.

Save Selection and restore

If the elements in the selection area are modified, such as adding new elements, changing element types, and so on, the original selection will be invalidated. Therefore, a useful technique is to save the selection Range before modifying the element, and then restore it after the modification is complete.

A complete example is as follows:

VarSelection=Window.GetSelection();VarRange=Selection.Getrangeat(0);Save All properties of RangeVarStartcontainer=Range.Startcontainer;VarStartoffset=Range.Startoffset;VarEndContainer=Range.EndContainer;VarEndoffset=Range.Endoffset;Perform element modification operations// ......Construct a new RangeVarNewrange=Document.Createrange();  //Note that a new selection must be created here to modify the invalid Newrange on the original range.  Setstart(startcontainer, startoffset);  Newrange.  SetEnd(endcontainer, endoffset);  Restores the selection selection.  Removeallranges();  Selection.  AddRange(newrange);              

It is important to note that some operations may automatically modify the selection, then the use of the above method will not achieve the purpose of restoring the selection. A common technique is to add a delay to the recovery selection, which is to addRange put the call into it setTimeout .

setTimeout(function(){ selection.addRange(newRange);}, 50);
Edit DOM, modify Style

A very important function of the text editor is to modify the style of the content, such as bold text, tilt, underline, and so on. It also includes modifying paragraphs to headings, block references, and so on. A more intuitive approach is to add styles as required by modifying elements as described above in saving and recovering selections. However, this method is actually more complicated to think about, especially in the paragraph, there are mixed styles, so that there is a pattern can be nested (such as a paragraph is bold and italic text), maintain the node relationship and clean up the empty nodes will be very cumbersome.

Fortunately, the browser provides us with a convenient interface to implement such a function. That is document.execCommand , this interface abstracts various operations into the form of commands. The following shows how to implement some basic functions.

Document.ExecCommand(' Bold '); Bold selectedDocument.ExecCommand(' Italic '); Tilt the selectedDocument.ExecCommand(' Underline '); Underline selectedDocument.ExecCommand(' Createlink ', True, ' Http://io-meter.com '); Add a link to the selected textDocument.ExecCommand ' unlink ' //unlink document. ( ' formatblock ' , true,  ' H1 ' ); //changes the paragraph of the cursor to a first-level title document. ( ' formatblock ' , true,  ' P ' ); //changes the cursor block to a paragraph              

In addition, the browser provides some editing commands, such as copy , cut and and paste so on. A complete list of commands can be found in this document

It is important to note that the various browsers support these commands somewhat differently, and therefore require extra attention. By understanding these commands, you have the basic knowledge to implement features such as modifying styles in the editor.

Listening for modifications

It is also necessary to say a little off-topic, in the past to listen to the user's modification of the text, is usually bound keydown events, in addition to the user may also choose and drag to change the content, may also add mouseup events, this method is inefficient and cumbersome, but also to modify the style of the element is powerless.

Fortunately, modern browsers provide a new mechanism for detecting content modifications, which is the Mutation Observer mechanism. In this regard, there is a good article worth reading: Detect, Undo and Redo DOM changes with Mutation observers.

Summarize

OK, knowing this knowledge, is it not so difficult to implement a simple Web text editor? Although there are some differences between browsers on these APIs, it has been widely used to implement online text editing functions.

In fact, if you focus only on modern browsers, it is not very difficult to achieve a beautiful and useful editing and writing tool like Medium!

Basic implementation principle of online text editor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.