程序员人生 网站导航

jquery文字插入光标插件,兼容FF,IE6+,Chrom

栏目:jquery时间:2014-04-22 06:38:10
这是一款jquery的插件,主要用途是将一段文本信息插入到光标处,这个功能听起来非常简单,但实际做出来可没那么容易,主要是因为兼容性的问题,后来查阅许多资料,才发现了这款短小精悍的jquery插件,和大家分享下吧.

(function($){
$.fn.extend({
insertAtCaret: function(myValue){
var $t=$(this)[0];
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}else if($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
this.focus();
$t.selectionStart = startPos + myValue.length;
$t.selectionEnd = startPos + myValue.length;
$t.scrollTop = scrollTop;
}else{
this.value += myValue;
this.focus();
}
}
});
})(jQuery);


用法:$(“select”).insertAtCaret(“text”);

如果你不习惯这样的方式,你可以将它改为正常的函数,例如:

function insertAtCaret(obj,myValue){
var $t=obj[0];
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}else if($t.selectionStart || $t.selectionStart == '0') {
var startPos = $t.selectionStart;
var endPos = $t.selectionEnd;
var scrollTop = $t.scrollTop;
$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
this.focus();
$t.selectionStart = startPos + myValue.length;
$t.selectionEnd = startPos + myValue.length;
$t.scrollTop = scrollTop;
}else{
this.value += myValue;
this.focus();
}
}

用法和上面的类似,insertAtCaret传入一个jquery对象,以及所要插入的文本,insertAtCaret($(“select”),”text”);
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐