//#region --文本框TextArea光标相关
var Pos = {
//IE版本号
getIEVer: function() {
var match = navigator.appVersion.match(/MSIEs+d+.0;/);
if (match == null) return -1;
return +match[0].match(/d+/)[0];
},
getPos: function(textBox) {
if (document.selection) {
var range = document.selection.createRange();
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
for (start = 0; range_all.compareEndPoints("StartToStart", range) < 0; start++) {
range_all.moveStart('character', 1);
}
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end++) {
range_all.moveStart('character', 1);
}
var selectionStart = start;
var selectionEnd = end;
//ie8-rn在move时会当成一个字符
if (this.getIEVer() > 8) {
var s1 = textBox.value.substr(0, selectionStart);
var s2 = textBox.value.substr(0, selectionEnd);
var m1 = s1.match(/rn/g);
var m2 = s2.match(/rn/g);
if (m1 != null) selectionStart += m1.length;
if (m2 != null) selectionEnd += m2.length;
}
return [selectionStart, selectionEnd];
}
else {
return [t.selectionStart, t.selectionEnd];
}
},
setPos: function(textBox, a, b) {
if (a && b) {
if (!(document.selection)) {
textBox.setSelectionRange(a, b);
}
else {
var range = textBox.createTextRange();
range.moveEnd('character', -textBox.value.length);
range.moveEnd('character', b);
range.moveStart('character', a);
range.select();
textBox.scrollTop = textBox.scrollTop2;
}
}
},
insert: function(textBox, value) {
var text = textBox.value;
var a = textBox.selectionStart2 || textBox.selectionStart;
var b = textBox.selectionEnd2 || textBox.selectionEnd;
var left = text.substr(0, a);
var right = text.substr(b, text.length);
b = a + value.length;
textBox.value = left + value + right;
this.setPos(textBox, b, b);
this.savePos(textBox);
},
savePos: function(textBox) {
if (document.selection) {
var pos = this.getPos(textBox);
textBox.selectionStart2 = pos[0];
textBox.selectionEnd2 = pos[1];
textBox.scrollTop2 = textBox.scrollTop;
}
}
};
jquery.fn.extend({
rememberPos: function () {
if (document.selection) {
this.each(function (i, el) {
$(el).keyup(function () { Pos.savePos(el); });
$(el).mouseup(function () { Pos.savePos(el); });
$(el).focus(function () {
Pos.setPos(el, el.selectionStart2, el.selectionEnd2);
});
});
}
}
});
$(function () {
$("textarea").rememberPos();
})
所以,只需要textBox.selectRange=document.selection.createRange().duplicate();将选取区间复制一份保存下来。