使用JS在textarea在光标处插入内容
来源:未知 责任编辑:责任编辑 发表时间:2014-05-10 12:24 点击:次
01
// 在光标处插入字符串
02
// myField 文本框对象
03
// myValue 要插入的值
04
function insertAtCursor(myField, myValue)
05
{
06
//IE support
07
if (document.selection)
08
{
09
myField.focus();
10
sel = document.selection.createRange();
11
sel.text = myValue;
12
sel.select();
13
}
14
//MOZILLA/NETSCAPE support
15
else if (myField.selectionStart || myField.selectionStart == '0')
16
{
17
var startPos = myField.selectionStart;
18
var endPos = myField.selectionEnd;
19
// save scrollTop before insert
20
var restoreTop = myField.scrollTop;
21
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
22
if (restoreTop > 0)
23
{
24
// restore previous scrollTop
25
myField.scrollTop = restoreTop;
26
}
27
myField.focus();
28
myField.selectionStart = startPos + myValue.length;
29
myField.selectionEnd = startPos + myValue.length;
30
} else {
// 在光标处插入字符串
02
// myField 文本框对象
03
// myValue 要插入的值
04
function insertAtCursor(myField, myValue)
05
{
06
//IE support
07
if (document.selection)
08
{
09
myField.focus();
10
sel = document.selection.createRange();
11
sel.text = myValue;
12
sel.select();
13
}
14
//MOZILLA/NETSCAPE support
15
else if (myField.selectionStart || myField.selectionStart == '0')
16
{
17
var startPos = myField.selectionStart;
18
var endPos = myField.selectionEnd;
19
// save scrollTop before insert
20
var restoreTop = myField.scrollTop;
21
myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
22
if (restoreTop > 0)
23
{
24
// restore previous scrollTop
25
myField.scrollTop = restoreTop;
26
}
27
myField.focus();
28
myField.selectionStart = startPos + myValue.length;
29
myField.selectionEnd = startPos + myValue.length;
30
} else {
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>