jquery文字插入光標插件,兼容FF,IE6+,Chrom
來源:程序員人生 發布時間:2014-04-22 06:38:10 閱讀次數:3260次
這是一款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”);
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈