这个问题已经被for example问过好几次了。但是,它们都没有解决在任意点插入的问题。
所以,如果你有一个文本输入或文本区域,以及一个没有在键盘上的符号的按钮(例如pi),或者一个按钮,如果突出显示文本,你会添加一个重音或其他指示符号。如何将其插入当前插入位置或选择?如果用户移动光标,并且当鼠标被单击时,这不一定是在末尾,您将失去对输入的关注,这将删除插入符号或选择。
<input id="formula" type="text">
<button onclick="insertIntoFormula">π</button>发布于 2017-10-27 02:01:27
听起来您需要.selectionStart (高亮显示文本的起始索引)和.selectionEnd (突出显示文本的结束索引)。如果它只是一个光标,它们都会返回它的位置。
function insertIntoFormula(specialChar) {
const textarea = document.getElementById('formula');
const insertStartPoint = textarea.selectionStart;
const insertEndPoint = textarea.selectionEnd;
let value = textarea.value;
// text before cursor/highlighted text + special character + text after cursor/highlighted text
value = value.slice(0, insertStartPoint) + specialChar + value.slice(insertEndPoint);
textarea.value = value;
}<input id="formula" type="text">
<!-- remember to actually pass the special character -->
<!-- (you *could* just get the innerText of the triggering button but I wouldn't recommend it) -->
<button onclick="insertIntoFormula('π')">π</button>
<button onclick="insertIntoFormula('é')">é</button>
https://stackoverflow.com/questions/46966177
复制相似问题