国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > jquery > jquery文字插入光标插件,兼容FF,IE6+,Chrom

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

来源:程序员人生   发布时间:2014-04-22 06:38:10 阅读次数:2884次
这是一款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”);
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生