当插入符号在内容可编辑div中时插入html [英] Insert html when the caret was in a content editable div

查看:114
本文介绍了当插入符号在内容可编辑div中时插入html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



编辑内容时,用户点击一个图标,弹出一个对话框,然后他输入url& amp; amp; ;在对话框中锚文本。这会导致可编辑div失去焦点,链接插入div的开头,而不是插入时。我尝试了很多东西,但我被卡住了。



rte我的可编辑内容div的ID

link_add对话框中按钮的ID

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

});

我也尝试了设置execcommand只用于一个div ,使用:

  function execCommandOnElement(el,commandName,value)

但是这会清空div并粘贴新的内容。

解决方案

我认为这是一个内嵌对话框(很像StackOverflow的链接对话框)重点,因此选择。解决方案似乎是保存和恢复选择。调用getSelection()以获取对选择的引用并保存 anchorNode anchorOffset focusNode focusOffset 属性,然后使用 collapse(anchorNode,anchorOffset)扩展(focusNode,focusOffset)以在您关注contenteditable div后恢复选择。 (如果你对这两个节点都不感兴趣,你可以 collapse(focusNode,focusOffset)。)


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.

解决方案

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).)

这篇关于当插入符号在内容可编辑div中时插入html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆