js在光标处插入...
时间:2010-08-09 来源:lulu_jiang
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label>
<textarea name="test1" id="test1" cols="45" rows="5">这是默认内容,嘿嘿,测试一下!</textarea>
<br />
<br />
<input name="tag" type="text" id="tag" value="AAA" />
<br />
<br />
<a href="javascript:void(0);" onclick="insertAtCursor($('test1'), $('tag').value);">插入</a>
</label>
</form>
</body>
</html>
<script type="text/javascript">
function $(id) { return document.getElementById(id); }
// 在光标处插入字符串
// myField 文本框对象
// 要插入的值
function insertAtCursor(myField, myValue)
{
//IE support
if (document.selection)
{
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0')
{
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
// save scrollTop before insert
var restoreTop = myField.scrollTop;
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
if (restoreTop > 0)
{
// restore previous scrollTop
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}
</script>