Article reproduced from: http://www.cnblogs.com/lucc/archive/2010/03/22/1692011.html
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 ("ID of iframe");
var editordoc = editor.contentWindow.document;
var editorwindow = Editor.contentwindow;
Editordoc.designmode = "on";
Editordoc.open ();
Editordoc.write ("
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 the 2.3 package a class that selects HTML for an operation
Because the methods of the Range object obtained in 2.1 vary widely in different browsers, the two operations mentioned in 2.1 and 2.2 are encapsulated by a class SelectionRange that operates on the selected HTML, with two methods, getselectedhtml, and replace, respectively, for Gets HTML and replaces HTML. The code is as follows:
The type used to record the browser var browser = {};
var ua = Navigator.userAgent.toLowerCase (); Browser.msie = (/msie ([\d.]
+)/). Test (UA); Browser.firefox = (/firefox\/([\d.]
+)/). Test (UA); Browser.chrome = (/chrome\/([\d.]
+)/). Test (UA);
Gets the HTML function getinnerhtml (nodes) {var builder = [] of multiple nodes; for (var i = 0; i < nodes.length i++) {if (nodes[i].nodevalue!= undefined) {Builder
. push (nodes[i].innerhtml); else {if (nodes[i].textcontent) Builder.push (Nodes[i].textcontent.replace (/\</ig, Functi
On () {return "<";}));
else if (nodes[i].nodevalue) Builder.push (nodes[i].nodevalue.replace (/\</ig, function () {return "<";});
} return Builder.join ("");} function SelectionRange (doc, range) {//Get the HTML for the selected content.
getselectedhtml = function () {if (range = null) return ""; if (Browser.msie) {if (range.htmltext!= undefined) return ranGe.htmltext;
else return ""; else if (Browser.firefox | | browser.chrome) {return getinnerhtml (Range.clonecontents (). chil
Dnodes);
else {return ""; HTML this to replace the selected content with HTML.
Replace = function (HTML) {if (range!= null) {if (Browser.msie) {
if (range.pastehtml!= undefined) {//currently selected HTML may be lost for some reason (such as clicking on another div), re-select
Range.Select ();
range.pastehtml (HTML);
return true; } else if (Browser.firefox | | browser.chrome) {if Range.deletecont
Ents!= undefined && range.insertnode!= undefined) {//Convert text HTML to DOM objects
var temp = doc.createelement ("DIV");
temp.innerhtml = html; var elems = []; for (var i = 0; i < temp.childNodes.length i++) {Elems.push (Temp.childnod
Es[i]);
//Delete the selected node range.deletecontents ();
Inserts the HTML-corresponding node (that is, all child nodes of temp) into range one by one, and removes the for (var i in elems) from temp
{Temp.removechild (elems[i]);
Range.insertnode (Elems[i]);
return true;
}} return false; }
}
At the same time, a function getselectionrange is implemented to get the SelectionRange object corresponding to the currently selected text.
function Getselectionrange (Win)
{
var range = null;
if (Browser.msie)
{
range = Win.document.selection.createRange ();
if (Range.parentelement (). Document!= Win.document)
{
range = null;
}
}
else if (Browser.firefox | | browser.chrome)
{
var sel = win.getselection ();
if (Sel.rangecount > 0) range = sel.getrangeat (0); else range = null;
}
return new SelectionRange (win.document, range);
2.4 Change the style of the selected HTML
Modifying the selected HTML style method is not complicated, just turn HTML into a DOM object, and then recursively set the value of each node's corresponding style, as follows:
function Setnodestyle (doc, node, name, value) {if (node.innerhtml = = undefined) {return node;
else {Node.style[name] = value;
for (var i = 0; i < node.childNodes.length i++) {var cn = Node.childnodes[i];
if (node.innerhtml!= undefined) {Setnodestyle (Doc, CN, name, value);
} return node;
} function SetStyle (doc, HTML, name, value) {var dom = doc.createelement ("DIV");
dom.innerhtml = html;
for (var i = 0; i < dom.childNodes.length i++) {var node = dom.childnodes[i]; if (node.innerhtml = = undefined) {//If it is a text node, the conversion is converted to span var span = doc.createelement ("Span
");
Span.style[name] = value;
if (node.nodevalue!= undefined) span.innerhtml = node.nodeValue.replace (/\</ig, function () {return "<";}); else if (node.textcontent!= undefined) span.innethtml = node.textContent.replace (/\</ig, function () {return "<";});
Replaces the text node Dom.replacechild (span, node);
else {Setnodestyle (doc, node, name, value);
} return dom.innerhtml; }
2.5 Example
Using the code above, you can easily implement an HTML editor, for example, the following code implementation sets the font size of the selected text to 32px:
var range = Getselectionrange (Editorwindow);
var html = SetStyle (Editordoc, range. Getselectedhtml (), "FontSize", "32px");
Range. Replace (HTML);
Similarly, you can set line spacing, indentation, insert pictures and other functions. 3. Summary
The code given in this article is compatible with Ie,firefox and chrome, and if there are other questions you can contact me via email or webim. 4. Examples
Another article from http://www.csharpwin.com/dotnetspace/5902r3668.shtml: imitate the online HTML editor
where Checkbrowsertype (), inserthtml (), KeyPress () functions need to be changed to fit FF and Chrome browsers.
var face_count=50;
var face_head= "images/";
var face_tail= ". gif";
function Checkbrowsertype () {var app=navigator.appname;
if (App.indexof (' Microsoft ')!=-1) {return 0;
} if (App.indexof (' Netscape ')!=-1) {return 1;
} function Easyeditor (Editorid) {This.editorid=editorid;
This.container=document.getelementbyid (This.editorid);
} easyeditor.prototype={Addfaceselector:function () {var selectorcontainer=document.createelement ("div");
var selectorimg=document.createelement ("img");
Selectorimg.src=face_head+ "Ec_1" +face_tail;
Selectorimg.id= "Faceselector_" +this.editorid;
Selectorcontainer.appendchild (SELECTORIMG);
This.container.appendChild (Selectorcontainer);
This.faceselector=document.getelementbyid ("Faceselector_" +this.editorid);
}, Addfaceimagediv:function () {var facesdiv=document.createelement ("div");
Facesdiv.id= "Facesdiv_" +this.editorid; Facesdiv.classname= "Facediv ";
for (Var i=1;i<=face_count;i++) {var faceimg=document.createelement ("img");
Faceimg.src=face_head+i+face_tail;
Faceimg.id= "Face_image_" +this.editorid+ "_" +i;
Faceimg.classname= "Facesimg";
Facesdiv.appendchild (FACEIMG);
This.container.appendChild (FACESDIV);
} This.facesdiv=document.getelementbyid ("Facesdiv_" +this.editorid);
}, Addframe:function () {var frame=document.createelement ("iframe");
Frame.id= "Frame_" +this.editorid;
frame.frameborder= "0";
frame.scrolling= "Auto";
Frame.marginwidth= "0";
Frame.id= "Frameid_" +this.editorid;
Frame.classname= "Editorframe";
This.container.appendChild (frame);
This.frame=document.getelementbyid (frame.id);
This.editorarea= This.frame.contentWindow;
This.editorArea.document.designMode = "on";
This.editorArea.document.contentEditable = true;
This.editorArea.document.open (); This.editorarEa.document.writeln ('
HTML section