DIV CSS 佈局教程網

在游標位置插入文字的 jQuery 外掛
編輯:JQuery特效代碼     

這個外掛的功能是:點擊某個元素時,讓輸入框在當前游標位置插入指定的文字。關鍵在於取得焦點位置,並針對不同瀏覽器做相容處理。

. 代碼如下:

(function($){
$.fn.extend({
"insert":function(value){
// 預設參數
value=$.extend({
"text":"123"
},value);
var dthis = $(this)[0]; // 將 jQuery 物件轉換為 DOM 元素
// IE 下
if(document.selection){
$(dthis).focus(); // 讓 textarea 取得焦點
var fus = document.selection.createRange();// 取得游標位置
fus.text = value.text; // 在游標位置插入值
$(dthis).focus(); // 再次取得焦點
}
// 火狐等標準瀏覽器
else if(dthis.selectionStart || dthis.selectionStart == '0'){
var start = dthis.selectionStart; // 焦點前坐標
var end = dthis.selectionEnd; // 焦點後坐標
// 在焦點前後之間插入傳入的值,再把新值賦回文本框
dthis.value = dthis.value.substring(0, start) + value.text + dthis.value.substring(end, dthis.value.length);
}
// 沒有定位游標的情況
else{
this.value += value.text;
this.focus();
};
return $(this);
}
})
})(jQuery)

主要思路

1. 點擊元素時先讓輸入框取得焦點,因為只有取得焦點才能輸入值。

IE 下用 document.selection.createRange();Firefox 則用 selectionStart 與 selectionEnd 取得焦點前後坐標。

2. 取得當前輸入框焦點的位置。

3. 把值插入到焦點位置。

4. 再次取得焦點,確保游標停留在輸入框內。

在線演示:https://demo.jb51.net/js/2012/myfocustext/

打包下載:https://www.jb51.net/jiaoben/44153.html

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved