The online HTML content editor provides the user with style control over text, such as text color, font size, and so on. Although there are many powerful editors (e.g. FCKEditor) on the web, there are many complicated configurations in use, and the code is often "bloated". The purpose of this article is to describe how to develop an HTML editor. Using the method described in this article, we can easily develop the HTML editor that satisfies your needs, and the code is comparatively concise. The following is an HTML editor developed using this method to achieve some simple features:
The development method is as follows:
1. Add an editable IFRAME
The 1th step in implementing the HTML editor is to place an editable iframe in the Web page to enter text, making the IFrame editable method fairly simple, by simply setting the designmode of the IFrame to on, as follows:
var editor = document.getElementById("IFRAME的ID");
var editorDoc = editor.contentWindow.document;
var editorWindow = editor.contentWindow;
editorDoc.designMode = "on";
editorDoc.open();
editorDoc.write(" editorDoc.close();
2. Set the style of selected text
The easiest way to set the method of selecting a text style is to use Document.execcommand, but the execcommand feature is limited and sometimes does not meet the requirements, such as: execcommand set font size can only be 1-7, cannot use pixel size, And if you click on a toolbar button to call ExecCommand the other div,iframe selection will disappear, then the call to ExecCommand is invalid. So this article introduces another method, the basic idea is as follows:
(1) Get the selected HTML;
(2) modify the HTML style;
(3) Replace the selected HTML with the modified HTML.
2.1 Getting the selected HTML
The way to get the selected HTML in a different browser is different, and you can use it in IE
var range = document.selection.createRange()
In Firefox,chrome, you use the
var range = window.getSelection().getRangeAt(0);
2.2 Replace the selected HTML
After you get the object that represents the selection by using the 2.1 method, you can call its method to replace the selected content. There is a difference in how to replace the selected HTML in different browsers, in IE, you can simply call range.pastehtml, and in firefox,chrome you use Range.deletecontents and Range.insertnode Two ways to implement