js文本框中控制光标位置和光标处插入文本
Posted on: 2013-10-11, Last modified: 2015-07-31, View: 1915
Posted on: 2013-10-11, Last modified: 2015-07-31, View: 1915
最近项目用到这个功能,主要是想自己设计一个编辑公式的文本框,网上很多方法,但是简单好使的不多,发现一篇博客,两个方法不错,学习一下:
IE和其他浏览器支持的方法不同,分别如下:
=IE支持document.selection
=Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd属性
具体代码:
function insertText(obj,str) { if (document.selection) { var sel = document.selection.createRange(); sel.text = str; } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') { var startPos = obj.selectionStart, endPos = obj.selectionEnd, cursorPos = startPos, tmpStr = obj.value; obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length); cursorPos += str.length; obj.selectionStart = obj.selectionEnd = cursorPos; } else { obj.value += str; } } function moveEnd(obj){ obj.focus(); var len = obj.value.length; if (document.selection) { var sel = obj.createTextRange(); sel.moveStart('character',len); sel.collapse(); sel.select(); } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') { obj.selectionStart = obj.selectionEnd = len; } }