可能重复:
Inserting a text where cursor is using Javascript/jquery
我在这里建立一个简单的模板系统。基本上我已经设置了将预设变量添加到textarea
的按钮。
问题是我希望能够在我的光标位置textarea
中添加文本。就像在编辑器窗口中点击stackoverflow上的帖子中的URL链接一样,链接将添加到光标所在的位置。
我该怎么做?它可以使用原型JS吗?
答案 0 :(得分:4)
这在IE中有点棘手,它在这种事情上做得非常糟糕。下面将在textarea或文本输入中的当前选择的末尾插入文本(如果选择了无文本,则在插入符号处插入),然后将光标放在文本后面:
演示:http://jsfiddle.net/RqTvT/1/
代码:
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
function offsetToRangeCharacterMove(el, offset) {
return offset - (el.value.slice(0, offset).split("\r\n").length - 1);
}
function setSelection(el, start, end) {
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
el.selectionStart = start;
el.selectionEnd = end;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
var startCharMove = offsetToRangeCharacterMove(el, start);
range.collapse(true);
if (start == end) {
range.move("character", startCharMove);
} else {
range.moveEnd("character", offsetToRangeCharacterMove(el, end));
range.moveStart("character", startCharMove);
}
range.select();
}
}
function insertTextAtCaret(el, text) {
var pos = getInputSelection(el).end;
var newPos = pos + text.length;
var val = el.value;
el.value = val.slice(0, pos) + text + val.slice(pos);
setSelection(el, newPos, newPos);
}
var textarea = document.getElementById("your_textarea");
insertTextAtCaret(textarea, "[INSERTED]");