问题
I have a problem. I've been trying to tackle it for a while now and I'm ready to explode. Here's my requirement:
I have an external toolbar (not part of YUI) above the editor that I want to use to insert HTML tags. The user should be able to click a link on the toolbar after which a few things may happen:
- If there's any selected text, this text gets wrapped into an HTML tag
- If there's no selected text, an empty HTML tag is inserted in the editor
- Regardless of the scenario, cursor MUST be placed inside the new element, so that when the user enters more text, it resides in the new element
The functionality is very similar to that of pressing "B" or "U" buttons on the editor's toolbar (now that I'm using this editor, it also does it well :-)). It preserves everything nicely. So far I'm able to do 1 or 2, but not 3. Step 3 is VERY important, because without it, user experience greatly suffers. I really need your assistance to implement it. Below is a simplified version of the method that performs the insertion (just inserting DIV for the sake of simplicity). this._oEditor - local instance of YUI Editor:
this._insertElement = function() {
var sSelection = this._oEditor._getSelection(); // Attempt to get selected text from the editor
if (sSelection == '') sSelection = ' '; // If nothing was selected, insert a non-breaking space
var sNewElt = '<div>' + sSelection + '</div>';
this._oEditor.execCommand('inserthtml', sNewElt);
this._oEditor.focus(); // This gives the editor focus, but places cursor in the beginning!
}
What is it that I must do to place the cursor in the right position? Is it even possible? Also, if there's a better way of implementing this, I'm all for it. Thank you!
回答1:
Here's complete the solution:
this._insertElement = function() {
var sSelection = this._oEditor._getSelection();
if (sSelection == '') sSelection = ' ';
var sNewElt = '<div>' + sSelection + '</div>';
this._oEditor.execCommand('inserthtml', sNewElt);
var pos = 1000; //pos determines where to place the cursor. if greater than the length of characters, it will place at the end.
if(this._oEditor.createTextRange) { //IE Specific code
var range = this._oEditor.createTextRange();
range.move("character", pos);
range.select();
} else if(this._oEditor.selectionStart) { //Works with Firefox and other browsers
this._oEditor.focus();
this._oEditor.setSelectionRange(pos, pos);
}
this._oEditor.focus();
}
回答2:
Placing the cursor requires different methods for different browsers. With IE you'll want to create a TextRange object, in Mozilla you can make use of window.find() or a Selection object, webkit/safari/chrome require yet another method.
来源:https://stackoverflow.com/questions/787996/yui-editor-rte-insert-html-element-and-place-cursor-inside