这近在项目中,用到了在输入框的光标处,插入指定的字符串,在这里分享给大家
javascript代码:
/** * 在光标处插入字符串 * myField: 文本框对象 * myValue: 要插入的值 */ 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(); } }
html代码:
<form> <textarea id=demo style="width: 500px; height: 300px">将鼠标定位到这里的任意位置,然后点击下面的按钮,即可测试插入效果</textarea> <input type=button onclick=insertAtCursor(document.getElementById('demo'),"【插入语句】") value=插入> </form>
以上为在光标处插入指定的字符串的功能实现,希望对大家有用。