php - Highlighting Text Under Div Tag - Stack Overflow

Lets say I have a div like this:<div id="test" class="sourcecode">"Some

Lets say I have a div like this:

<div id="test" class="sourcecode">
"Some String"
</div>

Is it possible to have css and js to highlight a portion of that string based on a search query?

Like if I was searching for the word Stri it would just highlight that part?

Lets say I have a div like this:

<div id="test" class="sourcecode">
"Some String"
</div>

Is it possible to have css and js to highlight a portion of that string based on a search query?

Like if I was searching for the word Stri it would just highlight that part?

Share Improve this question asked Feb 9, 2012 at 18:52 NovazeroNovazero 5536 silver badges24 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

You'll have to divide the text, separating the highlighted part into a <span>. Like this.

<div id="test" class="sourcecode">
"Some <span style="background-color:yellow">Stri</span>ng"
</div>

To do characters that represent HTML tags, if you have:

<div id="test" class="sourcecode">
    &lt;html&gt;String&lt;/html&gt;
</div>

...you can highlight the same way as before:

<div id="test" class="sourcecode">
    <span style="background-color:yellow">&lt;html&gt;Stri</span>ng&lt;/html&gt;
</div>

Try the jquery.highlight plugin.

Make a jQuery selector containing the div in which you want to highlight some text:

var $div = $('#test');

Then run the highlight plugin with the word(s) you wish to highlight

$div.highlight('Stri');

Also you should style the class "highlight" in your css, since that's the class the highlighter will give the highlighted text:

.highlight
{
    background-color: yellow;
    outline: 1px solid black;
}
<div id="test" class="sourcecode">
"Some String"
</div>

in javascript after getting search result.

<script>
  var test = $('test').innerHtml;
  var query= 'Str';
  var new_str = test.replace(query, '<font style="background:yellow;color:red;" >'+query+'</font>');
  $('test').innerHtml = new_str;
</script>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744903439a4600113.html

相关推荐

  • php - Highlighting Text Under Div Tag - Stack Overflow

    Lets say I have a div like this:<div id="test" class="sourcecode">"Some

    1天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信