[英]How to re-select the selected text in textarea by using javascript/jQuery?
我正在使用javascript和jQuery設計評論框。
我的頁面有一個textarea
和3個按鈕(粗體,下划線和斜體)。 如果用戶在文本區域中鍵入文本,選擇並單擊任何按鈕,則所選文本應變為 粗體 , 帶下划線或斜體 (我在下面有此功能)。
我的問題是,單擊帶有選定文本的按鈕后,盡管正確插入了html標簽,但是選擇丟失了。 也就是說,當我鍵入:“你好,我在這里。”時,選擇“我在這里”,然后單擊粗體按鈕。 我在這里變得粗體,但是如果我還要下划線或斜體 ,則必須重新選擇文本。
因此,我的問題是:如何重新選擇文本textarea
的選定文本?
我嘗試了myTextarea.select()
但是這段代碼將選擇textarea
的全部內容,而不僅是所選文本。
更新:
這是到目前為止我得到的:
var mystring = ""; // default string
/* Bold event */
function Bold()
{
var startString;
var endString;
var startPos; // starting position
var endPos; // ending position
var selectedText;
var temp = document.getElementById("myTextarea");
// check if text is selected
if(temp.selectionStart !== undefined)
{
startPos = temp.selectionStart;
endPos = temp.selectionEnd;
selectedText = temp.value.substring(startPos, endPos);
startString = temp.value.substring(0, startPos);
endString = temp.value.substring(endPos, temp.value.length);
}
$("#myTextarea").val(startString + "[B]" + selectedText + "[/B]" + endString); // rewrite textarea value
if(mystring !== "") // check if default string is NOT null, return null if it's the first clicked
{
mystring = mystring.replace(selectedText, "<b>" + selectedText + "</b>");
}
else
{
mystring = startString + "<b>" + selectedText + "</b>" + endString;
}
// write to preview panel
$("#preview").html(mystring);
$("#myTextarea").focus();
}
當我選擇“我在這里”的textarea
並點擊加粗按鈕上面的代碼將插入[B]
和[/B]
到textarea
和<b>
標簽到預覽面板。
要重新選擇文本,您可以執行以下操作:
temp.setSelectionRange(startPos, endPos + 6);
我添加了+ 6
因為您要插入6個新字符,因此我正在擴展選擇范圍以包括它們。 您還可以在startPos
和endPos
添加3(並讓字符包裝選擇內容) endPos
這是次於UX的明智選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.