[英]Insert value into TEXTAREA where cursor was
我有一個textarea和一個帶有值的div。 當我點擊一個值時,我將其插入textarea。 我需要將它插入我的光標在textarea中的位置。 為什么我說WAS? 因為當我將其移出並單擊要插入的值時,我認為它在文本區域中失去焦點。
所以,我的問題是,有沒有辦法“記住”textarea中的最新光標位置,然后在該位置插入我的值?
也許它可能是字符串中的字符編號?..目前我添加如下:
input.val( function( i, val ) { return val + " " + myInsert + " "; } );
我也使用jQuery,也許我可以使用它?
我編寫了一個跨瀏覽器的jQuery插件,用於處理textareas中的插入/選擇和稱為Rangy輸入的文本輸入 (可怕的名字,我真的應該想到更好的一個)。 結合這種方法和Edgar Villegas Alvarado的答案中的技巧應該可以解決問題 ,盡管在IE中, focusout
事件發生得太晚了,你需要使用專有的beforedeactivate
事件:
var $textBox = $("#foo");
function saveSelection(){
$textBox.data("lastSelection", $textBox.getSelection());
}
$textBox.focusout(saveSelection);
$textBox.bind("beforedeactivate", function() {
saveSelection();
$textBox.unbind("focusout");
});
稍后插入文本時,以下內容將在前一個光標位置插入文本(或覆蓋以前選擇的文本,如果用戶選擇了任何文本):
var selection = $textBox.data("lastSelection");
$textBox.focus();
$textBox.setSelection(selection.start, selection.end);
$textBox.replaceSelectedText("Some new text");
請參見這里的jsFiddle示例: http : //jsfiddle.net/rQXrJ/1/
以下是您嘗試執行的操作示例: http : //jsfiddle.net/J5Z2n/1/
Hello there my good friend.... how do you do
jQuery:
function insertAt (myField, myValue, startSel, endSel) { if (startSel || startSel == '0') { var startPos = startSel; var endPos = endSel; myField.val(myField.val().substring(0, startPos)+ myValue+ myField.val().substring(endPos, myField.val().length)); } else { myField.val() += myValue; } } // calling the function var targetBox = $('textarea#insert'), startSel, endSel; targetBox.bind('focusout', function() { //insertAtCursor(this, 'how do you do'); startSel = this.selectionStart; endSel = this.selectionEnd; }); $("#myvalue").click(function() { var myValue = $(this).text(); insertAt(targetBox, myValue, startSel, endSel); });
最初的功能是從這篇文章借來的http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
這應該會給你一個堅實的開端,我希望。 干杯
如果插入符號(光標)位於文本字段中的某個位置,則它在Javascript中注冊為空選擇。 也就是說,selectionStart和selectionEnd屬性是相同的。 您可以使用這些屬性來檢測插入符的位置。
顯然,selectionStart和selectionEnd在這里非常有用。 看看這個: http : //www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
您可以使用jQuery Caret插件來獲取/設置光標位置。
用法示例:
var cursorPosition = $("#textbox").caret().start);
你可以像這樣“存儲”這個位置:
$("#textbox").focusout(function(){
var cursorPosition = $(this).caret().start);
$(this).data("lastCursorPos", cursorPosition);
});
要檢索它(在div單擊事件上),請執行以下操作:
var lastCursorPosition = $("#textbox").data("lastCursorPos");
希望這可以幫助。 干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.