今天遇到一個需求露泊,當用戶在輸入框中輸入文本的時候步悠,點擊一個按鈕欣簇,獲取當前輸入框中光標的位置,并在當前位置中插入對應的文字或字符翘狱。
簡單整理了一下代碼:
<input id="title" name="title" type="text" value="" />
<button id="button">按鈕</button>
js代碼:
$(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();
}
}
})
$('#button').on('click', function() {
$("#title").insertAtCaret("ABC");
})
})
測試可以實現(xiàn)該功能秘案。