简体   繁体   English

突出显示TextArea中的特定文本

[英]highlight specific text in TextArea

I need to simulate a find and replace function in my webpage using javascript, no matter with find and replace, but the problem is how to highlight the matched search results inside the textArea before replacing them. 我需要使用javascript在我的网页中模拟查找和替换功能,无论是查找还是替换,但问题是如何在替换之前突出显示textArea中匹配的搜索结果。 I tried to replace matched results with with Bold Tag but it doesn't work because the textArea don't understand HTML tags. 我尝试用Bold Tag替换匹配的结果,但它不起作用,因为textArea不理解HTML标记。

I have used the following code: 我使用了以下代码:

function findMyText(searchTxt) {

 var textAreaTxt = "";

 textAreaTxt = document.getElementById("myTxtAreaID").value;
 var match = new RegExp(searchTxt, "ig");     
 var boldText = '<B>' + searchTxt+ '<\/B>';
 var replaced = textAreaTxt .replace(match, boldText);

 document.getElementById("myTxtAreaID").value= replaced;
}

is there any other way to highlight search results in textArea , or how to make textArea understand HTML Tags 有没有其他方法可以在textArea中突出显示搜索结果,或者如何使textArea理解HTML标签

Thanks in advance 提前致谢

t = document.getElementById("myTxtAreaID");
l = t.value.indexOf(searchText);
if(l!=-1){
t.selectionStart = l;
t.selectionEnd = l+searchText.length
}

What that code does is find the beginning of the found text and set the selectionStart and selectionEnd values for the textarea. 该代码的作用是找到找到的文本的开头,并为textarea设置selectionStart和selectionEnd值。 That simply selects the text as if the user had selected the text himself. 这只是选择文本,就像用户自己选择了文本一样。 Working demo here 在这里工作演示

I think the only possible ways to do that are: 我认为唯一可行的方法是:

  • use javascript canvas drawing to highlight text inside the textarea (?? quite complex i think) 使用javascript画布绘制突出显示textarea内的文本(我认为这很复杂)
  • use a "fake" textarea, built using an iframe, like what wysiwyg editors (ckeditor, tinymce, ..) do 使用iframe构建的“假”textarea,就像什么是wysiwyg编辑(ckeditor,tinymce,..)一样

A textarea can't render htmltags you have to hide your textarea and render the content in a div or an iframe. textarea无法呈现htmltags,您必须隐藏textarea并在div或iframe中呈现内容。 It's the techniques used by many wysiwyg editors. 这是许多所见即所得的编辑使用的技术。 Another way can be to use a contentEditable div 另一种方法是使用contentEditable div

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM