插入游标使用Javascript/jQuery的文本

插入游标使用Javascript/jQuery的文本

我有一个有很多文本框的页面。当有人单击某个链接时,我希望在光标所在的位置插入一两个单词,或者添加到具有焦点的TextBox中。

例如,如果光标/焦点放在一个标有“Apple”的文本框上,而他单击了一个链接,上面写着“[电子邮件]”,那么我希望文本框上写着‘Apple bob@example.com’。

我该怎么做?这是否可能,因为如果焦点放在收音机/下拉/非TextBox元素上怎么办?最后一个专注于文本框的东西能被记住吗?


拉丁的传说
浏览 481回答 3
3回答

一只名叫tom的猫

用这个,从这里:function insertAtCaret(areaId, text) {&nbsp; var txtarea = document.getElementById(areaId);&nbsp; if (!txtarea) {&nbsp; &nbsp; return;&nbsp; }&nbsp; var scrollPos = txtarea.scrollTop;&nbsp; var strPos = 0;&nbsp; var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?&nbsp; &nbsp; "ff" : (document.selection ? "ie" : false));&nbsp; if (br == "ie") {&nbsp; &nbsp; txtarea.focus();&nbsp; &nbsp; var range = document.selection.createRange();&nbsp; &nbsp; range.moveStart('character', -txtarea.value.length);&nbsp; &nbsp; strPos = range.text.length;&nbsp; } else if (br == "ff") {&nbsp; &nbsp; strPos = txtarea.selectionStart;&nbsp; }&nbsp; var front = (txtarea.value).substring(0, strPos);&nbsp; var back = (txtarea.value).substring(strPos, txtarea.value.length);&nbsp; txtarea.value = front + text + back;&nbsp; strPos = strPos + text.length;&nbsp; if (br == "ie") {&nbsp; &nbsp; txtarea.focus();&nbsp; &nbsp; var ieRange = document.selection.createRange();&nbsp; &nbsp; ieRange.moveStart('character', -txtarea.value.length);&nbsp; &nbsp; ieRange.moveStart('character', strPos);&nbsp; &nbsp; ieRange.moveEnd('character', 0);&nbsp; &nbsp; ieRange.select();&nbsp; } else if (br == "ff") {&nbsp; &nbsp; txtarea.selectionStart = strPos;&nbsp; &nbsp; txtarea.selectionEnd = strPos;&nbsp; &nbsp; txtarea.focus();&nbsp; }&nbsp; txtarea.scrollTop = scrollPos;}<textarea id="textareaid"></textarea><a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>
打开App,查看更多内容
随时随地看视频慕课网APP