正 文:
    JS实现TEXTAREA当前光标位置插入文字(兼容IE/CHROME/FIREFOX)。
    有的时候我们需要在textarea输入框里指定的位置(即光标位置)插入一些文字,在chrome或者firefox浏览器下,还挺好控制的,通过起始位置和结束位置  obj.selectionStart, endPos = obj.selectionEnd 实现当前光标定位。
    在IE下,却有点不同,一般情况下,我们可以通过以下代码实现在ie中当前光标位置插入文字:
obj.focus();
var sel = document.selection.createRange();
sel.text = str;
    但是更多的情况下是在当前页面的子页面 iframe 框架里操作的。这里飘易就发现有一个问题:当我们点击iframe页面里的按钮时,父页面所有元素已经失去了焦点,即光标。通过 document.selection.createRange() 获取的 光标位置是 元素的最开始位置,相当于光标在对象的最开始。
    那么,怎么解决呢? 在textarea失去焦点的时候,飘易建议大家用一个全局变量来保存光标位置。然后在子页面 iframe 里通过 window.parent.xxxFunction 方法调用父页面的函数。
    具体js代码如下:
//ie下 textarea失去焦点前要保存rang对象
var rie; //全局变量
function GetCursor() {
   	if (document.all) {//IE要保存Range
		var obj = document.getElementById('content');
		obj.focus(); 
		rie = document.selection.createRange();
    }
}
//光标定位与指定位置插入文本
//str ---   要插入的字符
function insertText(str) {
	var obj = document.getElementById('content');
    if (document.selection) { //ie
		obj.focus();//先激活当前对象
		rie.text = str;
    } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') { //非ie
        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;
    }
}
    然后在,在子页面里合适的按钮上添加 onclick 事件:
onclick="window.parent.GetCursor();"
    这样,我们就实现了兼容ie 、firefox、 chrome等浏览器下,在textarea指定光标位置插入文字的效果了。