在論壇回覆、聊天輸入等場景中,我們常需要在 textarea 的光標當前位置插入一段文本(例如表情、引用內容)。這需要精確獲取光標位置並進行插入,同時還要兼顧不同瀏覽器的差異。以下是一個完整的實現範例。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS在文本域鼠標指定位置插入文本</title>
<script type="text/javascript">
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) {
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}
</script>
</head>
<body>
<div style="width:500px;margin-left:auto;margin-right:auto;margin-top:100px;">
<textarea id="keleyi_com" style="width:340px; height:180px">
柯樂義 Javascript 在 textarea 光標處插入文本
</textarea>
<input type="button" onclick="insertAtCursor(document.getElementById('keleyi_com'),'www.keleyi.com')" value="插入文本" />
</div></body>
</html>
這個函數的關鍵在於跨瀏覽器的相容處理:IE 透過 document.selection 獲取當前選區並替換文本;而 Firefox、Netscape 等則透過 selectionStart 和 selectionEnd 屬性精準定位光標位置,插入後再將光標移動到插入內容之後。此外,代碼還特意保存了 scrollTop,避免插入後輸入框跳動,兼顧了使用體驗。