有很多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));相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!
推荐阅读:
判断日期是否有效的JavaScript代码段
Node.js的Event Loop详解
JavaScript运行机制之任务队列
怎样阻止django中form页面刷新后自动提交
Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1
违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务