var CodeArea = document.getElementById('CodeArea');
var res = GetSelectedText(CodeArea, 'index');//传index获取当前位置
ChangeSelectedText(CodeArea, str);//str传值
//获取光标位置,或者选中内容
function GetSelectedText(obj, type) {
debugger;
var userSelection;
if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
// 非IE浏览器
// 获取选区的开始位置
var startPos = obj.selectionStart,
// 获取选区的结束位置
endPos = obj.selectionEnd;
//console.log("非IE:")
//console.log("选区开始点:" + startPos + ',选区结束点:' + endPos)
if (type == "index") {
if (obj.selectionStart == obj.textLength) {
userSelection = "*#文本末尾#*";
}
} else {
userSelection = obj.value.substring(startPos, endPos)
}
} else if (document.selection) {
// IE浏览器
console.log("IE:")
userSelection = document.selection.createRange().text
}
return userSelection
}
//在光标位置插入新的内容
function ChangeSelectedText(obj, str) {
if (window.getSelection) {
// 非IE浏览器
//console.log("非IE:")
obj.setRangeText(str);
// 在未选中文本的情况下,重新设置光标位置
obj.selectionStart += str.length;
obj.focus()
} else if (document.selection) {
// IE浏览器
//console.log("IE:")
obj.focus();
var sel = document.selection.createRange();
sel.text = str;
}
}