这次给大家带来使文本高亮的javascript代码,用javascript使文本高亮的的注意事项有哪些,下面就是实战案例,一起来看一下。
有很多jquery的第三方库可以实现高亮文本的功能,但我更喜欢用下面这一小段javascript代码来实现这个功能,它非常短小,而且可以根据我的需要去进行灵活的修改,而且可以自己定义高亮的样式。下面这两个函数可以帮助你创建自己的文本高亮插件。
function highlight(text, words, tag) {
// default tag if no tag is provided
tag = tag || 'span';
var i, len = words.length, re; for (i = 0; i < len; i++) { // global regex to highlight all matches
re = new regexp(words[i], 'g'); if (re.test(text)) {
text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
}
}
return text;
}
你同样会需要取消高亮的函数:
function unhighlight(text, tag) { // default tag if no tag is provided
tag = tag || 'span'; var re = new regexp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g'); return text.replace(re, '');
}
使用方法:
$('p').html( highlight(
$('p').html(), // the text
['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight
'strong' // custom tag));
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
判断日期是否有效的javascript代码段
node.js的event loop详解
javascript运行机制之任务队列
怎样阻止django中form页面刷新后自动提交
以上就是使文本高亮的javascript代码的详细内容。