诀窍是可靠地获得光标位置。我从现有的SO 线程中找到了如何做到这一点。一旦有了光标位置,只需获取之前和之后的文本,然后在中间插入新值。
http://jsfiddle.net/Vr99u/1/
$("#mybutton").click( function() {
var pos = getCaret(document.getElementById('mytextarea'));
var currentText = $("#mytextarea").val();
var currentTextStart = currentText.substr(0, pos);
var currentTextEnd = currentText.substr(pos, currentText.length);
var newText = currentTextStart + $("#myselect").val() + currentTextEnd;
$("#mytextarea").val(newText); });
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}
var c = "\001",
sel = document.selection.createRange(),
dul = sel.duplicate(),
len = 0;
dul.moveToElementText(node);
sel.text = c;
len = dul.text.indexOf(c);
sel.moveStart('character',-1);
sel.text = "";
return len;
}