2012-04-25 8 views
4

HTMLコードは、私が上記のdivの中の特定の位置のいくつかのイベントに基づいて、いくつかの新しいテキストを挿入する必要があり、このcontenteditable div内の特定の位置にテキストを追加/挿入/更新する方法は?

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

のように見えます。 イベントは、関数updateDiv(txt、positon)を呼び出します。例えば、そうDIVができる

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

なるべき
updateDiv("more ",5);

を言う私には、JavaScriptとjQueryの多くを試みたが、何も動作するようには思えません。

+0

http://stackoverflow.com/questions/1882890/jquery-insert-text-to- textarea –

+0

@ RokoC.Buljan:いいえ、その質問はtextareasに関するものであり、contenteditableではありません。 –

+0

**別の文字列の位置xに文字列を挿入**:http://stackoverflow.com/questions/4364881/inserting-string-at-position-x-of-another-string – RASG

答えて

2

は、ここで私はそれをやった方法は次のとおりです。

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は 'アクションで' それを表示します。

編集this postに上記のコメントの方法でjsfiddleを更新しました。かなり滑らか!

+0

しかし、これはカーソルの位置を移動します。その 'contenteditable' div – MeetM

+0

@MeetM;はい、divの 'html()'を消去するとカーソル位置が移動します。あなたは、テキストを挿入する必要性を引き起こしているイベントは何も言及していません。キーボードイベントにバインドしようとしているはずです。しかし、誰かが入力している間に何かにテキストを挿入しているのであれば、それは気に入らないかもしれません。 – veeTrain

1

編集可能な内容<div>が常に1つのテキストノードで構成されている場合、これは比較的簡単で、以下のコードを使用できます。

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

そうでなければ、(彼らはIE < 9でサポートされていないことに注意してください)についてDOM Rangesを読み、コンテンツ内の文字のインデックスに対応する範囲を作成するためにthis answerようなものを使用して、insertNode()を使用する必要があります。

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

改行を含むcontentEditable divは、常により多くのノードを
の形式で持っていますか? 1つのテキストノードを持つことはどのように可能ですか? –

+1

@RafaelDiaz:質問内のコードには、単一のテキストノードを持つcontenteditable要素があります。一般に、明らかに、contenteditableを使用するアプリケーションは、書式設定なしで1つのテキストノードを編集することのみが可能な場合には、大いに役立つでしょう。 –

0

使用この機能:

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

と、この関数を使用します。

var oldstr=$('#txtarea').html(); 
var newstr='more'; 
var position = 5; 
$('#txtarea').html(oldstr.splice(position , newstr); 
関連する問題