加入收藏 | 设为首页 | 会员中心 | 我要投稿 厦门网 (https://www.xiamenwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 业界 > 正文

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

发布时间:2018-08-29 19:21:30 所属栏目:业界 来源:站长网
导读:这是一款jquery的插件,主要用途是将一段文本信息插入到光标处,这个功能听起来非常简单,但实际做出来可没那么容易,主要是因为兼容性的问题,后来查阅许多资料,才发现了这款短小精悍的jquery插件,和大家分享下吧. (function($){ $.fn.extend({ insertAtCaret:
这是一款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”);

(编辑:厦门网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读