(1):在光标处插入值
1 $.fn.extend({ 2 insertAtCursor : function(myValue) { 3 var $t = $(this)[0]; 4 if (document.selection) { 5 this.focus(); 6 sel = document.selection.createRange(); 7 sel.text = myValue; 8 this.focus(); 9 } else if ($t.selectionStart || $t.selectionStart == '0') { 10 var startPos = $t.selectionStart; 11 var endPos = $t.selectionEnd; 12 var scrollTop = $t.scrollTop; 13 $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); 14 this.focus(); 15 $t.selectionStart = startPos + myValue.length; 16 $t.selectionEnd = startPos + myValue.length; 17 $t.scrollTop = scrollTop; 18 } else { 19 this.value += myValue; 20 this.focus(); 21 } 22 } 23 });
(2):获取textarea选中的值
1 $.fn.selection = function(){ 2 var s,e,range,stored_range; 3 if(this[0].selectionStart == undefined){ 4 var selection=document.selection; 5 if (this[0].tagName.toLowerCase() != "textarea") { 6 var val = this.val(); 7 range = selection.createRange().duplicate(); 8 range.moveEnd("character", val.length); 9 s = (range.text == "" ? val.length:val.lastIndexOf(range.text)); 10 range = selection.createRange().duplicate(); 11 range.moveStart("character", -val.length); 12 e = range.text.length; 13 }else { 14 range = selection.createRange(), 15 stored_range = range.duplicate(); 16 stored_range.moveToElementText(this[0]); 17 stored_range.setEndPoint('EndToEnd', range); 18 s = stored_range.text.length - range.text.length; 19 e = s + range.text.length; 20 } 21 }else{ 22 s=this[0].selectionStart, 23 e=this[0].selectionEnd; 24 } 25 var te=this[0].value.substring(s,e); 26 return {start:s,end:e,text:te}; 27 };