Rangy - 替换innerHTML时恢复光标位置 [英] Rangy - restore cursor position when replacing innerHTML
问题描述
我使用Rangy来选择和恢复光标位置。
I am using Rangy to select and restore the cursor position.
这是一个很好的工作,但它没有被设计用于以编程方式操纵用户输入在DIV的innerHTML中替换较短的字符串。
It does an excellent job but it has not been designed for when user input is manipulated programmatically and a shorter string is replaced in the innerHTML of the DIV.
我在jsbin上创建了一个示例,显示当用户在选择结束时键入空格时会发生什么,空格是以编程方式删除:
http://jsbin.com/ebeqoj/4/edit
I created an example on jsbin showing what happens when user types a space at the end of the selection and the space is stripped out programmatically: http://jsbin.com/ebeqoj/4/edit
替换的innerHTML比Rangy尝试恢复的内容短,因此失败,DIV失去了焦点。
The replaced innerHTML is shorter than the one Rangy tries to restore so it fails and the DIV loses focus.
我会很乐意如何处理这个建议。例如,有没有办法指示Rangy在新字符串的末尾还原光标? (我尝试使用 rangy.getSelection()。move(character,userInput2.length-1)
没有成功)
I would appreciate suggestions on how to handle this. For example, is there a way to instruct Rangy to restore the cursor at the end of the new string? (I have tried using rangy.getSelection().move("character", userInput2.length-1)
without success)
谢谢
推荐答案
将插入符放在< div> ;
很简单:
var sel = rangy.getSelection();
sel.selectAllChildren(el);
sel.collapseToEnd();
对于更一般的情况,您可以创建一个包含从< div>
到插入位置,使用Rangy范围的 text()
方法获取文本,删除空格从该文本并衡量其长度。演示:
For the more general case, you can create a range that encompasses the content from the start of the <div>
to the caret position, get its text using the text()
method of Rangy ranges, remove white space from that text and measure its length. Demo:
http://jsbin.com/ ebeqoj / 5 / edit
这篇关于Rangy - 替换innerHTML时恢复光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!