Comme vous le dites, vous pouvez déjà insérer une balise sur le curseur, je vais commencer à partir de là. La première chose à faire est de donner un identifiant à votre tag lorsque vous l'insérez. Vous devriez avoir quelque chose comme ceci:
<div contenteditable='true' id='status'>I went shopping with <a href='#' id='atagid'>Jane</a></div>
Voici une fonction qui devrait placer le curseur juste après la balise.
function setCursorAfterA()
{
var atag = document.getElementById("atagid");
var parentdiv = document.getElementById("status");
var range,selection;
if(window.getSelection) //FF,Chrome,Opera,Safari,IE9+
{
parentdiv.appendChild(document.createTextNode(""));//FF wont allow cursor to be placed directly between <a> tag and the end of the div, so a space is added at the end (this can be trimmed later)
range = document.createRange();//create range object (like an invisible selection)
range.setEndAfter(atag);//set end of range selection to just after the <a> tag
range.setStartAfter(atag);//set start of range selection to just after the <a> tag
selection = window.getSelection();//get selection object (list of current selections/ranges)
selection.removeAllRanges();//remove any current selections (FF can have more than one)
parentdiv.focus();//Focuses contenteditable div (necessary for opera)
selection.addRange(range);//add our range object to the selection list (make our range visible)
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createRange();//create a "Text Range" object (like an invisible selection)
range.moveToElementText(atag);//select the contents of the a tag (i.e. "Jane")
range.collapse(false);//collapse selection to end of range (between "e" and "</a>").
while(range.parentElement() == atag)//while ranges cursor is still inside <a> tag
{
range.move("character",1);//move cursor 1 character to the right
}
range.move("character",-1);//move cursor 1 character to the left
range.select()//move the actual cursor to the position of the ranges cursor
}
/*OPTIONAL:
atag.id = ""; //remove id from a tag
*/
}
EDIT: Testé et un script fixe. Cela fonctionne certainement dans IE6, chrome 8, firefox 4, et opera 11. Ne pas avoir d'autres navigateurs en main pour tester, mais il n'utilise pas de fonctions qui ont changé récemment, donc il devrait fonctionner dans tout ce qui supporte contenteditable.
Ce bouton est pratique pour les tests: <input type='button' onclick='setCursorAfterA()' value='Place Cursor After <a/> tag' >
Nico
Avez-vous trouvé une autre explication jamais? J'ai posté une question similaire sur http://stackoverflow.com/questions/3764273/jquery-facebook-like-autosuggest-triggered-by et http://stackoverflow.com/questions/3972014/get-caret-position-in- contenteditable-div mais pas de chance ... – Bertvan
Je peux certainement sympathiser avec un manque d'aide sur contenteditable! J'ai dû travailler beaucoup sur moi-même récemment. –