在輸入框或文字區域中,有時我們需要把某段文字精準地插入到當前光標位置,而不是簡單地附加到末尾。下面這個函式就能做到,並兼顧了 IE 與標準瀏覽器:
/**
*往輸入域中插入字符串(光標所在位置)
*@param $t document.getElementById('fieldId')
*@param myValue 要插入的值
**/
function addSplitToField($t,myValue){
if (document.selection) {
$t.focus();
sel = document.selection.createRange();
sel.text = myValue;
$t.focus();
}else if($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
this.focus();
$t.selectionStart = startPos + myValue.length;
$t.selectionEnd = startPos + myValue.length;
$t.scrollTop = scrollTop;
}else{
$t.value += myValue;
$t.focus();
}
}
它的運作方式是:先判斷瀏覽器類型,舊版 IE 使用 document.selection,標準瀏覽器則透過 selectionStart 與 selectionEnd 取得光標位置,把新內容拼接進去後,再把光標移到插入內容之後,並保留原本的捲動位置。