[英]Highlighting Text Under Div Tag
Lets say I have a div like this: 可以说我有一个像这样的div:
<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? 可以让CSS和JS根据搜索查询突出显示该字符串的一部分吗?
Like if I was searching for the word Stri it would just highlight that part? 就像我在搜索Stri一词一样,它只会突出显示该部分?
You'll have to divide the text, separating the highlighted part into a <span>
. 您必须将文本分开,将突出显示的部分分成
<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: 如果有,要做代表HTML标签的字符:
<div id="test" class="sourcecode">
<html>String</html>
</div>
...you can highlight the same way as before: ...您可以像以前一样突出显示:
<div id="test" class="sourcecode">
<span style="background-color:yellow"><html>Stri</span>ng</html>
</div>
Try the jquery.highlight plugin. 尝试使用jquery.highlight插件。
Make a jQuery selector containing the div in which you want to highlight some text: 创建一个jQuery选择器,其中包含要突出显示某些文本的div:
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: 另外,您还应该在CSS中设置“突出显示”类的样式,因为该类是荧光笔会提供突出显示的文本的类:
.highlight
{
background-color: yellow;
outline: 1px solid black;
}
<div id="test" class="sourcecode">
"Some String"
</div>
in javascript after getting search result. 在获得搜索结果后的javascript中。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.