Core code:
(function($){
$.fn.extend({
"insert":function(value){
//Default parameter
value=$.extend({
"text":"123"
} ,value);
var dthis = $(this)[0]; //Convert jQuery object to DOM element
//Under IE
if(document.selection){
$(dthis ).focus(); //Input element textara gets focus
var fus = document.selection.createRange();//Gets cursor position
fus.text = value.text; //Insert value at cursor position
$(dthis).focus(); ///Input element textara gets focus
}
//Standard under Firefox
else if(dthis.selectionStart || dthis.selectionStart == '0 '){
var start = dthis.selectionStart; //Get the coordinates before focus
var end =dthis.selectionEnd; //Get the coordinates after focus
//The following sentence should be before the focus, and the position after the focus, insert the value we passed in. Then assign the new value to the text box
dthis.value = dthis.value.substring(0, start) value.text dthis.value. substring(end, dthis.value.length); }
// When the input element textara does not have a cursor positioned
else{
this.value = value.text; this.focus();
};
return $(this); At this time, let an input box insert the specified value. ?
1. When an element is clicked, the input box should be focused, because only when the focus is obtained can a value be entered in it;
IE: document.selection.createRange()
FF :var start = dthis.selectionStart; //Get the coordinates before focus
var end =dthis.selectionEnd; //Get the coordinates after focus
2. Get the position of the focus of the current input box
3. Insert the value Go to the focus position of the input box;
4. Get the focus again; make sure the cursor is in the input box
Online demo:
http://demo.jb51.net/js/2012/myfocustext/
Package download:
http://www.jb51.net/jiaoben/44153.html