How does iframe . contentWindow . document . execCommand work?
im trying to find out how this text editor work, iv been scanning through the script and can't seem to understand it.
first this is the link for the 开发者_运维知识库demo
what i can't understand is when you click the bold button which triggers this
$('.bold', tb).click(function(){ formatText(iframe, 'bold');return false; });
and then it gets send to the formatText function, and thats where i get lost, becuase thiers no mention of adding <strong></strong>
tags to the text in the textarea, im really curious to know how it works, thanks.
function formatText(iframe, command, option) {
iframe.contentWindow.focus();
try{
iframe.contentWindow.document.execCommand(command, false, option);
}catch(e){console.log(e)}
iframe.contentWindow.focus();
formatText is not a default jQuery function. I took the above from the js source of the editor. The first thing it does is focus on the iframe area where your text resides. You're not really typing in a textarea field, but rather in an iframe contentEditable div <div contentEditable="true"></div>
since textarea does not support rich text editing. The function then issues the contentEditable exexCommand to make the selected text Bold.
You can view a list of all execCommands at http://help.dottoro.com/larpvnhw.php
It uses document.execCommand which is a tool for turning pages into 'editable' mode. Have a read through the description and Command Identifiers.
It originated from IE but has been adopted into most modern browsers.
Here's the function which uses it.
function formatText(iframe, command, option) {
iframe.contentWindow.focus();
try{
iframe.contentWindow.document.execCommand(command, false, option); //Right here
}catch(e){console.log(e)}
iframe.contentWindow.focus();
}
That text editor does not use <textarea>
s, it uses <iframe>
s.
Some browsers implement a special API for WYSIWYG editing. First, it requires setting designMode = "On" on document object. After that you can use pre-defined commands that do the formatting, like
document.execCommand('bold', false, null);
You can find some information in the Midas specification, that Firefox uses. IE has very similar API and even more pre-defined commands.
精彩评论