2015-07-20 22 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

相关问题