2016-10-19 63 views
0

文本區域的代碼。如何在文本框中突出顯示文字?

<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

我不認爲你將能夠突出顯示文本框的多個部分。你也無法做任何事情,而不是選擇一段文字。如果要突出顯示多個選擇,則最好使用DIV作爲文本並使用HTML操作來添加高亮,例如以某種樣式在'span'中打包匹配。 – musefan

回答

1

你實際上不能在textarea中渲染標記。但是,您可以僞造它由

  • 精心定位的textarea
  • 後面一個div保持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您的文本區域後面。
  • 而「onpaste」在文本區域,文本區域的內容複製到DIV的innerHTML
  • 搜索從提示在div的文本,並添加標記標記它

請參考codepen鏈接瞭解詳細信息