JS实现点击插入内容到文本框并替换

 1 /**
 2 *使用方法 
 3 *$(文本域选择器).insertContent("插入的内容"); 
 4 *$(文本域选择器).insertContent("插入的内容",数值); //根据数值选中插入文本内容两边的边界, 数值: 0是表示插入文字全部选择,-1表示插入文字两边各少选中一个字符。 
 5 **/ 
最近需要这个功能,然后在网上查询资源,发现这个挺好用,转过来分享一下:
下面为JS全部内容: 6 //在光标位置插入内容, 并选中 7 (function($) { 8 $.fn.extend({ 9 insertContent: function(myValue, t) { 10 var $t = $(this)[0]; 11 if (document.selection) { //ie 12 this.focus(); 13 var sel = document.selection.createRange(); 14 sel.text = myValue; 15 this.focus(); 16 sel.moveStart('character', -l); 17 var wee = sel.text.length; 18 if (arguments.length == 2) { 19 var l = $t.value.length; 20 sel.moveEnd("character", wee + t); 21 t <= 0 ? sel.moveStart("character", wee - 2 * t - myValue.length) : sel.moveStart("character", wee - t - myValue.length); 22 sel.select(); 23 } 24 } else if ($t.selectionStart || $t.selectionStart == '0') { 25 var startPos = $t.selectionStart; 26 var endPos = $t.selectionEnd; 27 var scrollTop = $t.scrollTop; 28 $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); 29 this.focus(); 30 $t.selectionStart = startPos + myValue.length; 31 $t.selectionEnd = startPos + myValue.length; 32 $t.scrollTop = scrollTop; 33 if (arguments.length == 2) { 34 $t.setSelectionRange(startPos - t, $t.selectionEnd + t); 35 this.focus(); 36 } 37 } 38 else { 39 this.value += myValue; 40 this.focus(); 41 } 42 } 43 }) 44 })(jQuery);

 

posted @ 2016-08-05 17:57  帅仔很忙  阅读(1428)  评论(0编辑  收藏  举报