简体   繁体   English

如何在特定位置的contenteditable div中添加/插入/更新文本?

[英]How to add / insert / update text inside contenteditable div at a particular position?

The HTML code looks like this HTML代码如下所示

<div id="txtarea" contenteditable="true">Some text</div>

I have to insert some new text based on some event at a particular position in the above div. 我必须根据上面div中特定位置的某些事件插入一些新文本。 The event calls the function say updateDiv(txt, positon). 该事件调用函数说updateDiv(txt,positon)。 For example it says 例如它说
updateDiv("more ",5);

So the div should become be 所以div应该成为

<div id="txtarea" contenteditable="true">Some more text</div>

I tried a lot of javascript and jquery but nothing seem to work. 我尝试了很多javascript和jquery但似乎没什么用。

Here's how I did it: 我是这样做的:

var position = 5,
    txt = "more ";
var current = $("#txtarea").html();
//alert(current.substring(0, position))
var endVal = current.substring(position);
var newValue = current.substring(0, position) + txt + endVal;
$("#txtarea").html(newValue);​

jsfiddle displaying it 'in action'. jsfiddle显示它'在行动'。

Edit : Updated the jsfiddle with the approach listed in a comment above to this post . 编辑 :更新的jsfiddle以上在评论中列出的方法这篇文章 Pretty slick! 很漂亮!

If the content of your editable <div> always consists of a single text node, this is relatively simple and you can use the code below. 如果可编辑<div>的内容始终由单个文本节点组成,则相对简单,您可以使用下面的代码。

var div = document.getElementById("txtarea");
var textNode = div.firstChild;
textNode.data = textNode.data.slice(0, 5) + "more " + textNode.data.slice(5);

Otherwise, you'll need to read about DOM Ranges (note that they are not supported in IE < 9) and use something like this answer to create a range corresponding to character indices within the content and then use insertNode() . 否则,您需要阅读有关DOM范围的信息 (请注意它们在IE <9中不受支持)并使用类似此答案的内容创建与内容中的字符索引相对应的范围,然后使用insertNode()

var div = document.getElementById("txtarea");
var range = createRangeFromCharacterIndices(div, 5, 5);
range.insertNode(document.createTextNode("more "));

use this function : 使用此功能:

String.prototype.splice = function( position, newstring ) {
    return (this.slice(0,position) + newstring + this.slice(position));
};

and use this function as : 并使用此功能:

var oldstr=$('#txtarea').html();
var newstr='more';
var position = 5;
$('#txtarea').html(oldstr.splice(position , newstr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM