本文实例讲述了javascript识别网页关键字并进行描红的方法。分享给大家供大家参考,具体如下:
这里演示javascript智能识别网页关键字并加红显示出来,相信这个效果大家不陌生吧,用js加红关键字要比程序控制输出好得多,必竟将一部分功能交给了客户浏览器,相应减轻了服务器的压力。
运行效果截图如下:
在线演示地址如下:
http://demo.jb51.net/js/2015/js-keyword-show-red-color-codes/
具体代码如下:
<!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><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>js查询替换关键字</title><style type="text/css">span{color:#f00;font-weight:bold;}</style></head><body><p>我是标题:这里是文字介绍!</p><p>我是老二:老二的描述性文字。</p><script type="text/javascript">var ps = document.getelementsbytagname('p');for(i=0;i<ps.length;i++){ var text = ps[i].innerhtml; var index = text.indexof(':'); var span = document.createelement('span'); span.innerhtml = text.substring(0,index+1); ps[i].innerhtml = text.substring(index+1); ps[i].insertbefore(span,ps[i].firstchild);}</script></body></html>
以上就是本章的全部内容,更多相关教程请访问javascript视频教程!