13
还有就是HTML这样的:恢复光标位置改变CONTENTEDITABLE后
<div contenteditable="true" class="value research-form thumbnail">
Some text here
</div>
和DIV的内容应动态地突出了一些话,而用户类型,例如制造类似:
<div contenteditable="true" class="value research-form thumbnail">
Some text here <span style="background-color: yellow">highlight</div> it
</div>
<script>
$(document).ready(function() {
var input = $('#textarea').on('input', function (event) {
var newText = input.text().replace('highlight', '<span style="background-color: yellow">highlight</div>');
input.html($.parseHTML(newText));
});
});
</script>
但是有一个问题:当我刷新div中的文本时,光标在输入文本的开始处移动。
改变contenteditable值后,有什么办法恢复光标位置吗?或者,也许还有其他方式来获得相同的效果?
尝试保存光标位置(见http://stackoverflow.com/questions/4767848/get-caret-cursor-position-in-contenteditable-area-containing- html-content),然后在input.html(...)后面设置它(请参阅http://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div)。 我认为你在这里还有其他问题:在你的例子中,每次编辑文本时,“高亮”单词将被包裹在一个新的跨度中。在添加新跨度之前,可能应该用占位符替换包裹的单词,然后将占位符替换回来。 – Qwerty 2014-10-01 10:52:17
如果您的解决方案符合您的期望,则应将其添加为答案并将其选中。 http://stackoverflow.com/help/self-answer – 2016-01-27 17:10:34
@JasonSperske完成 – Tdm 2016-01-29 12:40:14