更改innerHTML后,更改contenteditable div中的光标位置 [英] Change cursor position in the contenteditable div after changing innerHTML

查看:855
本文介绍了更改innerHTML后,更改contenteditable div中的光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的contenteditable div,里面有一些文字。
在onkeyup事件中,我想根据正则表达式替换div的整个内容(innerHTML)。 例如,

HTML:

 一些文字,更多文字和$甚至更多文字

函数,我打算用$($甚至在上面的例子中)获取所有文本并将其包装在span标记中:

  div.onkeypress = function(){
div.innerHTML.replace(/(some_regexp)/,< span class = '类' > $ 1·/跨度>中);
};

问题出在这样的替换光标跳转到div的开头。我希望它保持原来的位置。



我想我必须在更改之前保存光标的坐标,然后以某种方式使用它们来设置光标,但我该怎么办它? :)



我试过保存范围对象,但编辑后我认为它指向无处。

谢谢! / p>

解决方案

问题是你正在更新整个innerHTML,但只有一小部分正在改变。您不能使用正则表达式和批量替换。您需要扫描div并查找匹配项,从中创建文本范围并用span覆盖内容。请参阅 http://www.quirksmode.org/dom/range_intro.html ,以编程方式创建一个范围。



然而,如果光标位于要替换的文本中,我认为这将不起作用,这是一个开始。


I have a simple contenteditable div with some text in it. On onkeyup event i want to replace whole content (innerHTML) of the div based on regex.

For example,

HTML:

some text, more text and $even more text

Function in which i plan to get all text with $ ($even in example above) and wrap it in span tag:

div.onkeypress = function() { 
     div.innerHTML.replace(/(some_regexp)/, "<span class='class'>$1</span>"); 
}; 

The problem is after such replacement cursor jumps to the start of the div. I want it to stay where it was before.

I imagine i have to save coordinates of the cursor before change and then somehow using them set cursor back but how can i do it? :)

I tried saving range object but after editing i believe it points to nowhere.

Thanks!

解决方案

The problem is that you're updating the whole innerHTML, but only a small part of it is changing. You can't use a regular expression and o a bulk replace. You need to scan the div and look for matches, create text ranges out of them and wrap the content with the span. See http://www.quirksmode.org/dom/range_intro.html , Programmatically creating a Range.

However, I think this won't work if the cursor is in the text to be replaced, it's a start though.

这篇关于更改innerHTML后,更改contenteditable div中的光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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