function inyectarTexto(elemento,valor){
var elemento_dom=document.getElementsByName(elemento)[0];
if(document.selection){
elemento_dom.focus();
sel=document.selection.createRange();
sel.text=valor;
return;
}if(elemento_dom.selectionStart||elemento_dom.selectionStart=="0"){
var t_start=elemento_dom.selectionStart;
var t_end=elemento_dom.selectionEnd;
var val_start=elemento_dom.value.substring(0,t_start);
var val_end=elemento_dom.value.substring(t_end,elemento_dom.value.length);
elemento_dom.value=val_start+valor+val_end;
}else{
elemento_dom.value+=valor;
}
}
你可以这样使用它:
<a href="javascript:void(0);" onclick="inyectarTexto('nametField','hello world');" >Say hello world to text</a>
function getCaret(el) {
if (el.prop("selectionStart")) {
return el.prop("selectionStart");
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
B)在插入符号位置附加文字:
function appendAtCaret($target, caret, $value) {
var value = $target.val();
if (caret != value.length) {
var startPos = $target.prop("selectionStart");
var scrollTop = $target.scrollTop;
$target.val(value.substring(0, caret) + ' ' + $value + ' ' + value.substring(caret, value.length));
$target.prop("selectionStart", startPos + $value.length);
$target.prop("selectionEnd", startPos + $value.length);
$target.scrollTop = scrollTop;
} else if (caret == 0)
{
$target.val($value + ' ' + value);
} else {
$target.val(value + ' ' + $value);
}
};
C)例子
$('textarea').each(function() {
var $this = $(this);
$this.click(function() {
//get caret position
var caret = getCaret($this);
//append some text
appendAtCaret($this, caret, 'Some text');
});
});