Input Box 光標位置與插入


部份代碼,因為網上都是 textarea 的資料為主,
所以就得自己動手寫一個,以下是大約的方法,筆記一下.
基本是基於 textarea 來改造的,不過主要 IE 部份重寫了..
有空再來完善..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function insertSmile(NewCode) {
var postText = document.getElementById("tmp_says");
postText.focus();

if(os.isIE) {
if(postText.value.length < 3000) {
// 取得目前光標位置 (限制範圍)
range = document.selection.createRange();
if (postText.createTextRange().inRange(range)) {
range.setEndPoint("StartToStart", postText.createTextRange());
cusPos= range.text.length;

// 取得開頭到光標位置的文字
startPart = postText.value.substr(0, cusPos);

// 取得光標到結尾位置的文字
endPart = postText.value.substr(cusPos, postText.value.length);

// 插入文字
postText.value = startPart + NewCode + endPart;

// 設置光標在加入文字後的位置
range = postText.createTextRange();
range.collapse(true);
range.moveStart('character', cusPos + NewCode.length);
range.select();
}
}
else {
if(postText.createTextRange){
postText.focus();
document.selection.createRange().duplicate().text=NewCode;
}
else {
postText.value+=NewCode;
}
}
}
else {
pos = postText.selectionStart;
postText.value = postText.value.substr(0, pos) + NewCode + postText.value.substr(postText.selectionEnd);
postText.selectionStart = pos + NewCode.length;
postText.selectionEnd = postText.selectionStart;
}
postText.focus();
}

參考 : http://blog.csdn.net/starnight_cbj/archive/2008/12/28/3628406.aspx