js通过createRange方法,在输入框中的光标所在位置插入内容,兼容Firefox、Chrome、IE等浏览器,示例代码如下:
CSS:
textarea{ width: 500px; height: 300px; border: 1px solid #eee; } button{ border: 1px solid #eee; padding: 5px; margin-top: 20px; }
HTML:
<div> <p>点击插入字符按钮,向输入框内插入“♥”</p> <textarea></textarea> </div> <button type="button" onclick="insertHTML()">插入字符</button>
JavaScript:
function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; sel.select(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; // save scrollTop before insert var restoreTop = myField.scrollTop; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); if (restoreTop > 0) { // restore previous scrollTop myField.scrollTop = restoreTop; } myField.focus(); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; myField.focus(); } } function insertHTML(){ insertAtCursor(document.querySelector('textarea'), '❤'); }