2015-07-20 27 views
0

例如,假設我想強調的文本塊中的一個文本字段,然後按一個鏈接與<highlight>...</highlight>標籤(例如<highlight>(highlighted text appears here)</highlight>)封閉文本 - 例如爲:如何使用JavaScript將帶突出顯示的文字與某些標籤放在textarea中?

<textarea id="comment-body"></textarea> 
<a href="#" class="highlight-words" onclick="highlightWords()">Highlight</a> 

function highlightWords(){ 
    // code for enclosing highlighted text in textarea appears here 
} 

任何想法?

+0

我真的不知道爲什麼,當問題和答案都非常不同,這被標記爲重複。這是我在StackOverflow上看到的最奇怪的事情之一。我很高興在過度熱情的節制結束這個問題之前得到了我想要的答案。 – sjsc

回答

1

您可以使用JavaScript selectionStartselectionEnd屬性來查找選定的文本。這將爲您提供開始和結束索引,您可以使用它來更新字符串。

<textarea id="comment-body"></textarea> 
 
<a href="#" class="highlight-words">Highlight</a>

$('a.highlight-words').click(function() { 
 
    var textComponent = document.getElementById('comment-body'); 
 
    var fullText = document.getElementById('comment-body').value; 
 
    var selectedText; 
 
    var startPos = textComponent.selectionStart; 
 
    var endPos = textComponent.selectionEnd; 
 
    selectedText = textComponent.value.substring(startPos, endPos) 
 

 
    if (selectedText.length > 0) { 
 
    var newStr = fullText.substr(0, endPos) + '</highlight>' + fullText.substr(endPos); 
 
    newStr = newStr.substr(0, startPos) + '<highlight>' + newStr.substr(startPos); 
 

 
    textComponent.value = newStr; 
 
    } 
 
});

演示在這裏:http://jsfiddle.net/rqy7e0qh/

+0

太棒了!第一次完美運作。謝謝安德魯! :) – sjsc

相關問題