我正在处理“添加评论框”,其中包含一些功能,如将[b]text[/b]
更改为带粗体样式的文本等。问题是当javascript中的str.replace操作完成了写入区域中的光标回到开始位置时。如何在更新输入值时保持光标位置
$('#comment').keyup(function() {
var str = document.getElementById("comment").innerHTML;
if (str.indexOf('[b]') >= 0 && str.indexOf('[/b]') >= 0) {
var start_pos = str.indexOf('[b]') + 3;
var end_pos = str.indexOf('[/b]', start_pos);
var text_to_get = str.substring(start_pos, end_pos)
res = str.replace("[b]" + text_to_get + "[/b]", "<b>" + text_to_get + "</b>");
document.getElementById("comment").innerHTML = res;
}
});
这不是关于'str.replace'的问题,而是'innerHTML'的行为。 – isherwood
[这个问题和答案](http://stackoverflow.com/questions/7745867/how-do-you-get-the-cursor-position-in-a-textarea)有帮助吗? – Blazemonger
[在contenteditable div中保持游标位置]的可能重复(http://stackoverflow.com/questions/16194364/maintain-cursor-position-in-contenteditable-div) – isherwood