您的位置:首页 > Web前端 > JQuery

jQuery文字高亮插件,使用简单,功能强大,支持FF/IE等主流浏览器

2010-06-01 23:45 981 查看
jQuery文字高亮插件,使用简单,功能强大,支持FF/IE等主流浏览器

源码:

jQuery.fn.extend({
highText : function (searchWords, css) {
return this.each(function(){
$(this).html(function high(replaced, search, css){
var pattarn = search.replace(//b(/w+)/b/g, "($1)").replace(//s+/g, "|");
return replaced.replace(new RegExp(pattarn, "ig"), function(keyword){
return $("<span>" + keyword + "</span>").css(css).outerHTML();
});
}($(this).text(), searchWords, css));
});
},
outerHTML : function(s) {
return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
}
});


测试:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> jQuery文字高亮插件,使用简单,功能强大,支持FF/IE等主流浏览器 </title>
</head>
<body>
源字符串:<input name="src" type="text" size="30" value="ABCDEFGHIJKLMNOPQISTUVWXYZ0123456789中华人民共和国" /><br />
搜索字符串:<input id="sea" name="search" type="text" size="30" /><br />
<div class="h">ABCDEFGHIJKLMNOPQISTUVWXYZ0123456789中华人民共和国</div>
<div class="h">ABCDEFG0123456789中华PQISTUVW人民HIJKLMNOXYZ共和国</div>
<div class="h">ABCDEFGHIJKLMNOPQI789中华人民STUVWXYZ0123456共和国</div>
<div class="h">ABCDKLMNOPQISTUVWXY9中EFGHIJ华人民Z012345678共和国</div>
<div class="h">ABCDEFGHUVWXYZ0123456789中华人IJKLMNOPQIST民共和国</div>
<div id="h">ABCDEFM89中华TUVWXYZ01人民NOPQIS23GHIJKL4567共和国</div>
<input type="button" value="高亮" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("input[type='button']").click(function(){
$(".h").highText($("#sea").val(), {color : "#F00", "font-size" : "150%"});
});
jQuery.fn.extend({ highText : function (searchWords, css) { return this.each(function(){ $(this).html(function high(replaced, search, css){ var pattarn = search.replace(//b(/w+)/b/g, "($1)").replace(//s+/g, "|"); return replaced.replace(new RegExp(pattarn, "ig"), function(keyword){ return $("<span>" + keyword + "</span>").css(css).outerHTML(); }); }($(this).text(), searchWords, css)); }); }, outerHTML : function(s) { return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html(); } });
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐