日期:2014-05-18  浏览次数:20434 次

在光标处插入文本
<asp:TextArea     id= "tr "   runat= "server "/>
js
<script>
AddText()
{

}
</script>

请问谁有代码?

------解决方案--------------------
给一个textbox的.textarea好像不行. <input type= "text " id= "t1 " style= "width:200px;height:200px "> </input> <input type= "button " onmousedown= "javascript:return AddText(); " value= "Add " /> <script> function AddText() { var s=document.selection.createRange(); s.setEndPoint( "StartToStart ",document.getElementById( "t1 ").createTextRange()) var pos = s.text.length; s.text += "aaa "; } </script>
------解决方案--------------------
提供一个DEMO, 不知道能不能满足要求 ~

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml " >
<head>
<title> Insert Text into TextBox at Cursor Position by Javascript </title>
<script type= "text/javascript ">
var cursPos;
function insertText() {
var txt1 = document.getElementById( "Text1 ");
var txt2 = document.getElementById( "Text2 ");
//debugger;
if(!cursPos) TraceCursorPosition(txt2); // 获取光标位置
alert(cursPos.start + " " + cursPos.end);
txt2.value = txt2.value.slice(0, cursPos.start) +
txt1.value + txt2.value.slice(cursPos.end)
}

function TraceCursorPosition(obj)
{
//debugger;
cursPos = $CursorPosition(obj);
}

// 返回光标所在位置
/*
** source: http://blog.csdn.net/liujin4049/archive/2006/09/19/1244065.aspx
** acknowledges for Marshall
*/
function $CursorPosition(textBox){
var start = 0, end = 0;
//如果是Firefox(1.5)的话,方法很简单
if(typeof(textBox.selectionStart) == "number "){
start = textBox.selectionStart;
end = textBox.selectionEnd;
}
//下面是IE(6.0)的方法,麻烦得很,还要计算上 '\n '
else if(document.selection) {
var range = document.selection.createRange();
if(range.parentElement().id == textBox.id) {
// create a selection of the whole textarea
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
//两个range,一个是已经选择的text(range),一个是整个textarea(range_all)
//range_all.compareEndPoints()比较两个端点,如果range_all比range更往左(further to the left),则
//返回小于0的值,则range_all往右移一点,直到两个range的start相同。
// calculate selection start point by moving beginning of range_all to beginning of range
for (start=0; range_all.compareEndPoints( "StartToStart ", range) < 0; start++)
range_all.moveStart( 'character ', 1);
// get number of line breaks from textarea start to selection start and add them to start
// 计算一下\n
for (var i = 0; i <= start; i ++) {
if (textBox.value.charAt(i) == '\n ')
start++;
}
// create a selection of the whole textarea