Nowadays, website development is increasingly promoting user experience, and there are more and more tools to provide users with convenience, and the online HTML content editor should be considered one of the "older" ones. Those with simple functions can provide users with text style control, such as text color, font size, etc.; while those with complex functions can even provide powerful functions similar to Word. Although there are many open source editors now, not many are really easy to use, so their improvement work is always in progress.
Most editors on the Internet today have very powerful functions. Relatively speaking, they also require a lot of configuration during use. Of course, the code will naturally be "bloated". If we don't need such a powerful editor, we can implement one ourselves, because the code is not complicated. The following is a bit of personal experience, for reference only (taking ExtJS HTMLEditor as an example).
1. Initialization. When the page has finished loading, add an IFrame to the page (optional). What should be noted here is that to determine the status of the page, wait until the page is completely loaded before proceeding to prevent errors in which certain elements cannot be found.
2. Open the editing function. Make the IFrame editable (the code below comes from ExtJS’s HTMLEditor):
//Get the document object of iframe
getDoc: function(){
return Ext.isIE ? this.getWin().document: (this.iframe.contentDocument || this.getWin().document);
},
//Open the document object and write initialization content to it to be compatible with FireFox
doc = this.getDoc();
doc.open();
doc.write('
This way you can write content into this simple editor.
3. Get the content of the editor, the code is as follows:
//Return content
return content;
4. Add style settings. Although the above editor implements basic functions, it is really too simple. Some simple style implementations should be added. The document's execCommand method makes this idea possible.
//Change the selected font to bold, Ctrl-B
execCmd('bold');
//Underline, Ctrl-U
execCmd('underline');
//Change to italics, Ctrl-I
execCmd('italic');
//Set the color of the text
execCmd('forecolor', Ext.isSafari || Ext.isIE ? '#' color : color);
//Insert a piece of content at the cursor
function insertAtCursor(text){
//To obtain the win object, refer to the code above
if(Ext.isIE){
win.focus();
var r = doc.selection.createRange();
If(r){
r.collapse(true);
r.pasteHTML(text);
}else if(Ext.isGecko || Ext.isOpera){
win.focus();
execCmd('InsertHTML', text);
}else if(Ext.isSafari){
execCmd('InsertText', text);
}
}
//Underline
doc.queryCommandState('underline');
//italic
doc.queryCommandState('italic');
One final reminder: Be sure to pay attention to browser compatibility issues, and don’t wait until the end to test compatibility. For such a large amount of JavaScript code, adjustments are more painful.