2016-10-19 3 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

実際にテキストエリア内でマークアップをレンダリングすることはできません。ただし、

  • によってそれ偽物慎重例えばdiv要素

にあなたのハイライトのマークアップを追加テキストエリア

  • のようにdiv要素の内側のHTMLは、同じキープ
  • テキストエリアの背後にある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> 
    

    とスタイルマークタグ

    あなたの条件のために0
    mark { 
        border-radius: 3px; 
        color: transparent; 
        background-color: #b1d5e5; 
    } 
    

    • はマークタグ
    • のCSSを追加するには、テキスト領域の背後にあるdiv要素を追加します。
    • テキストエリアの「onpaste」しばらく、divの中に、プロンプトからのテキストのためのdivのinnerHTMLの
    • 検索にテキストエリアの内容をコピーして

    は、詳細についてはcodepenのリンクを参照してくださいマークのタグを追加します

  • 関連する問題