保持光标位置在contenteditable div [英] Maintain cursor position in contenteditable div
问题描述
首先,这与以下相似:
如何使用html子元素在contenteditable div中找到插入符号位置?
基本上,我在twitter中写入类似于新的tweet编辑器的内容。在 div
与 contentEditable
设置,我正在解析文本。当我检测到我认为是一个URL时,我将该文本分开,并在div内输入一个< a>
标签(例如输入的转到www.google.com
成为转到< a href ='..'> www.google.com< / a>
Basically, I'm writing something similar to the new tweet editor in twitter. Inside a div
with contentEditable
set on, I am parsing the text. When I detect what I think is a URL, I strip that text out and enter into an <a>
tag inside the div (e.g. entered message of go to www.google.com
becomes Go to <a href='..'>www.google.com</a>
. BUT, the caret position is lost when I do that.
使用@ Tim-Down在其他SO帖子中的建议只会在你不要编辑DOM(正如他所说),我正在编辑DOM,所以插入符号位置丢失。
Using the suggestion by @Tim-Down in those other SO posts will only work as long as you don't edit the DOM (as he says). I AM editing the DOM, so the caret position is lost.
是否可能(理想情况下不使用Rangy库引用)通过编写当前代码来实现这一点。
Is it possible (ideally without using the Rangy library referenced) to achieve this by working on the current code.
我现在的代码(来自其他SO帖子):
The code that I have at the moment (from the other SO posts):
var saveSelection, restoreSelection;
if (window.getSelection) {
// IE 9 and non-IE
saveSelection = function(win) {
var sel = win.getSelection(), ranges = [];
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
}
return ranges;
};
restoreSelection = function(win, savedSelection) {
var sel = win.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSelection.length; i < len; ++i) {
sel.addRange(savedSelection[i]);
}
};
} else if (document.selection && document.selection.createRange) {
// IE <= 8
saveSelection = function(win) {
var sel = win.document.selection;
return (sel.type != "None") ? sel.createRange() : null;
};
restoreSelection = function(win, savedSelection) {
if (savedSelection) {
savedSelection.select();
}
};
}
我使用这样:
$('div').on('keyup paste', function(e) {
var ranges = saveSelection(window);
var newContent = /* Get the new HTML content */;
$('div').html(newContent);
restoreSelection(window, ranges);
});
推荐答案
如果用户看到的文本保持不变(其中您的问题似乎暗示是这种情况),您可以使用基于字符偏移的解决方案。我已经在Stack Overflow的其他地方发布了一些代码:
If the text the user sees remains the same (which your question seems to imply is the case), you could use a character offset-based solution. I've posted some code for that elsewhere on Stack Overflow:
https: //stackoverflow.com/a/13950376/96100
我最近还回答了一个相关问题:
I also answered a related question quite recently:
这篇关于保持光标位置在contenteditable div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!