Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

jquery - Insert html when the caret was in a content editable div

I want to insert some html in a contenteditable div.

When editing the content, the user clicks on an icon, a dialog pops and he enters the url & anchor text in the dialog. This causes that the editable div loses its focus and the link is inserted at the beginning of the div, not when the caret was. I tried many things but I'm stuck.

"rte" id of my editable content div

"link_add" id of button in dialog

$('#link_add').click(function (e)
{       
    $('#rte').focus();                  
    document.execCommand('insertHTML', false, 'html content test');         
    close_modal ();
    e.preventDefault();

});

I also tried the solution from set execcommand just for a div, using:

function execCommandOnElement(el, commandName, value)

But this empties the div and just paste the new content.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I take it this is an "inline" dialog (much like StackOverflow's link dialog, for instance), which moves the focus and therefore the selection. The solution seems to be to save and restore the selection. Call getSelection() to get a reference to the selection and save the anchorNode, anchorOffset, focusNode and focusOffset properties and then use collapse(anchorNode, anchorOffset) and extend(focusNode, focusOffset) to restore the selection once you have focused the contenteditable div. (If you're not interested in both nodes you could just collapse(focusNode, focusOffset).)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...