给你:在线Demo地址:https://codepen.io/lssssi-163-com/pen/XWedBKZ <input type="text" id="ipt" /> <button id="btn">点击插入文字</button>const btn = document.getElementById("btn"); const ipt = document.getElementById("ipt"); const insertAtCursor = (elem, value) => { var field = elem; var newValue = ""; // IE support if (document.selection) { field.focus(); var sel = document.selection.createRange(); sel.text = newValue = value; sel.select(); } else if (field.selectionStart || field.selectionStart === 0) { var startPos = field.selectionStart; var endPos = field.selectionEnd; var restoreTop = field.scrollTop; newValue = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length); if (restoreTop > 0) { field.scrollTop = restoreTop; } field.value = newValue; field.dispatchEvent(new CustomEvent("input")); field.focus(); setTimeout(function () { field.selectionStart = startPos + value.length; field.selectionEnd = startPos + value.length; }, 0); } else { newValue = field.value + value; field.value = newValue; field.dispatchEvent(new CustomEvent("input")); field.focus(); } }; btn.onclick = () => { insertAtCursor(ipt, "文字"); };
给你:
在线Demo地址:https://codepen.io/lssssi-163-com/pen/XWedBKZ