2017-08-12 40 views
0

我有一個textarea用戶可以在其中輸入文本。用戶也可以按下按鈕來添加圖片和鏈接等內容。該按鈕即提示他們輸入鏈接,然後在光標位於的textarea 中輸入正確的html。一個工作的代碼示例是這樣的:移動光標到最後一個輸入

jQuery('input#btn').click(function(e) { 
    var link = prompt("Please paste the link", "http://"); 
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>'); 
}); 

.insertAtCaret()功能是由Daniel貝克for another question of mine麻煩創建的。它會在textarea中查找光標的位置,以便可以在此處添加html塊。

但jQuery添加了這個HTML塊後,遊標不再在textarea中,但焦點現在在被按下的按鈕。我希望光標保持在按下此按鈕之前(在添加的html塊之後)。

是否可以在textarea中查找最後輸入的文本,然後可以在那裏移動光標?

請注意,此輸入可能位於textarea的已寫入文本中的任何位置。

+0

那麼你怎麼樣設置一個屬性給已經給出模糊方法的元素。然後,您可以通過屬性 –

+0

搜索元素,我可以從頭頂開始考慮至少兩種不同的方法。首先將聚焦相同的元素,但根據插入的長度移動焦點X個字符。這需要在當前在textarea中插入內容的實際功能中完成。 您也可以嘗試搜索您輸入的任何文本,並在該內容的最後一個字符後面設置焦點 - 基本讀取textarea的內容,搜索您剛剛輸入內容的匹配項,然後從那裏開始。 – junkfoodjunkie

回答

1

首先你必須把焦點放回你的文本區域。

var te = document.getElementById('id1'); 
te.focus(); 

然後將光標設置到特定位置。

var mySavedPosition = 3 // or whatever it was before 
te.selectionStart = mySavedPosition; 
te.selectionEnd = mySavedPosition; 

那就是它。

因此,在你的榜樣它可能看起來像在這裏:

jQuery('input#btn').click(function(e) { 
    var link = prompt("Please paste the link", "http://"); 
    var te = document.getElementById('id1'); 
    var pos = te.selectionStart; 
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>'); 
    te.selectionStart = pos; 
    te.selectionEnd = pos; 
}); 

很遺憾,但我不是jQuery的朋友,所以我只使用本地JS。

更新

我忽略了你想讓光標在插入位置的末尾。由於我不知道插入文本的長度,我最好從最後得到這個位置。

jQuery('input#btn').click(function(e) { 
    var link = prompt("Please paste the link", "http://"); 
    var te = document.getElementById('id1'); 
    var pos = te.textLength - te.selectionStart; 
    jQuery('textarea#id1').insertAtCaret('<a href="'+link+'">link text</a>'); 
    te.selectionStart = te.textLength - pos; 
    te.selectionEnd = te.textLength - pos; 
}); 
相關問題