【发布时间】:2014-09-01 04:37:39
【问题描述】:
我正在开发一个简单的(我认为的)文字处理器。它使用 contenteditable。我有一个想要始终突出显示的单词列表。
<article contenteditable="true" class="content">
<p>Once upon a time, there were a couple of paragraphs. Some things were <b>bold</b>, and other things were <i>italic.</i></p>
<p>Then down here there was the word highlight. It should have a different color background.</p>
</article>
所以基本上我需要的是一种在<span> 标签中包装单词的方法。事实证明,这比我预期的要困难。
这是我首先尝试的:
var text = document.querySelector('article.content').innerHTML
start = text.indexOf("highlight"),
end = start + "highlight".length;
text = text.splice(end, 0, "</span>");
text = text.splice(start, 0, "<span>");
document.querySelector('article.content').innerHTML = text;
它使用splice 找到的here 方法。
它完全符合我的需要,但有一个大问题:光标移动了。因为所有的文本都被替换了,光标失去了它的位置,这对于文本编辑器来说不是一件好事。
我也尝试过几次使用document.createRange,但问题是,虽然给定范围的起点和终点仅包括可见字符,但text.indexOf("highlight") 给出的索引包括标签等。
一些我不确定如何执行的想法:
- 使用上面的代码找出光标开始的位置并再次将其放置在那里
- 找出
createRange和indexOf之间的索引差异 - 也许已经有一个库具有这种我无法找到的功能
感谢您的帮助!
【问题讨论】:
标签: javascript html text contenteditable cursor-position