如何在文本框中突出显示文本?

时间:2016-10-19 09:05:27

标签: javascript html

文字区域的代码。

<div>
      <textarea id="ta" onpaste="functionFind(event)"></textarea>
</div>

将要执行的功能

function functionFind(pasteEvent)
{    
    var textareacont = (pasteEvent.originalEvent || pasteEvent).clipboardData.getData("text/html");
    var tofindword = prompt("Enter the word to find");
    if(textareacont.includes(tofindword ))
    {
        //What code do I write here so that all the word that matches "tofindword" gets highlighted in the same textbox only
    }
}

一旦我们将某些内容粘贴到文本框中,该功能就会被执行,所有匹配的单词只能在同一个文本框中突出显示。

1 个答案:

答案 0 :(得分:1)

您无法在textarea中实际呈现标记。但是,您可以通过

伪造它
  • 小心地将一个div放在textarea后面
  • 保持div的内部HTML与textarea相同
  • 将高亮标记添加到div

例如:

<div class="container">
    <div class="backdrop">
    <div class="highlights">
            <mark>This</mark> demo shows how to highlight bits of text within a textarea. <mark>Alright</mark>, that's a lie. <mark>You</mark> can't actually render markup inside a textarea. <mark>However</mark>, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. <mark>JavaScript</mark> takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. <mark>Hit</mark> the toggle button to peek behind the curtain. <mark>And</mark> feel free to edit this text. <mark>All</mark> capitalized words will be highlighted.
        </div>
    </div>
<textarea>
    This demo shows how to highlight bits of text within a textarea. Alright, that's a lie. You can't actually render markup inside a textarea. However, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there. JavaScript takes care of syncing the content and scroll position from the textarea to the div, so everything lines up nicely. Hit the toggle button to peek behind the curtain. And feel free to edit this text. All capitalized words will be highlighted.</textarea>
</div>

设置标记标记的样式

mark {
  border-radius: 3px;
  color: transparent;
  background-color: #b1d5e5;
}

根据您的要求,

  • 为标记标记添加css
  • 在文字区域后面添加div。
  • while textarea中的'onpaste',将文本区域的内容复制到div的innerHTML中
  • 从div中的提示中搜索文本并为其添加标记标记

有关详细信息,请参阅codepen链接