现在我有一个可编辑的 DIV。我已经能够相当容易地获得字符索引,但我无法将其插入正确的位置。我可以使用 splice 来插入它,只要没有 HTML 元素,它就可以工作。那么我该如何忽略标签呢?看起来使用正则表达式可能是可能的,但处理有点太多。看起来我可以使用 Range,但是我在理解 JavaScript Range 方面遇到了很多困难。这是基本思想:
<div class="toinsert" contenteditable="true">Some Text <strong>here</strong></div>
.
var charisat = 8; //SOME NUMBER
var dividedcontent = []; //DIVIDE CONTENT, BY RANGE OR REGEX
$('.toinsert').html(dividedcontent[0] + '<em>other text</em>' + dividedcontent[1]);
最佳答案
不确定是否有更好的方法,但粗略的方法是这样的
var charisat = 8;
addContent($('<em>other text</em>'), charisat, $('.toinsert'))
function addContent($content, pos, $el) {
$el.contents().each(function() {
if (this.nodeType == Node.TEXT_NODE) {
var text = $(this).text();
if (text.length >= pos) {
var $obj = $();
$obj = $obj.add(document.createTextNode(text.substring(0, pos)));
$obj = $obj.add($content);
$obj = $obj.add(document.createTextNode(text.substring(pos)));
$(this).replaceWith($obj);
return;
} else {
pos -= text.length;
}
} else if (this.nodeType == Node.ELEMENT_NODE) {
pos = addContent($content, pos, $(this));
}
return pos;
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toinsert" contenteditable="true">Some Text <strong>here</strong>
</div>
关于Javascript通过char Ref将元素插入到带有子元素的可编辑DIV中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938765/