我有一个页面,上面有很多文本框.当有人单击链接时,我希望在光标所在的位置插入一两个单词,或者将其附加到具有焦点的文本框中.
例如,如果光标/焦点在一个文本框上,上面写着‘Apple’,而他点击了一个链接,上面写着‘[email]’,那么我希望文本框上写着‘apple bob@example.com’.
我怎么才能做到这一点呢?既然焦点放在单选/下拉/非文本框元素上,这可能吗?上一个聚焦在文本框上的内容还能被记住吗?
我有一个页面,上面有很多文本框.当有人单击链接时,我希望在光标所在的位置插入一两个单词,或者将其附加到具有焦点的文本框中.
例如,如果光标/焦点在一个文本框上,上面写着‘Apple’,而他点击了一个链接,上面写着‘[email]’,那么我希望文本框上写着‘apple bob@example.com’.
我怎么才能做到这一点呢?既然焦点放在单选/下拉/非文本框元素上,这可能吗?上一个聚焦在文本框上的内容还能被记住吗?
使用这个,从here开始:
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
if (!txtarea) {
return;
}
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false));
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart('character', -txtarea.value.length);
strPos = range.text.length;
} else if (br == "ff") {
strPos = txtarea.selectionStart;
}
var front = (txtarea.value).substring(0, strPos);
var back = (txtarea.value).substring(strPos, txtarea.value.length);
txtarea.value = front + text + back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var ieRange = document.selection.createRange();
ieRange.moveStart('character', -txtarea.value.length);
ieRange.moveStart('character', strPos);
ieRange.moveEnd('character', 0);
ieRange.select();
} else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
<textarea id="textareaid"></textarea>
<a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>