js搜索全文高亮显示
方法一:
<body> <div id="content"> 长河浸月千仞孤鸿渡弹指点晕开残风无数棋盘纵横交错几回命途倾盖如故谁人识曲误衣袂拂弦 弦动晦朔荣枯 </div> <input type="text" id="text" placeholder="请输入关键字"/> <input type="button" id="button" value="确定"/> <script> var content = document.getElementById("content"); var contents = content.innerHTML; var text = document.getElementById("text"); var button = document.getElementById("button"); button.onclick = function() { var value = text.value; var values = contents.split(value); content.innerHTML = values.join('<span style="background:red;">' + value + '</span>'); }; </script> </body>
方法二:
<!DOCTYPE HTML> <html lang="en"> <meta http-equiv="Content-Type" content="text/html; charset=gdk" /> <head> <title>检索关键字</title> <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> </head> <body> <div style="width:100%; height:100px"> <input id="key" type="text"/><input type="button" value="检索" onclick="search()"/> </div> <div id="result"> 抱一抱就当作从没有在一起 好不好要解释都已经来不及算了吧我付出过什么没关系 我忽略自己就因为遇见你没办法好可怕那个我不像话 一直奋不顾身是我太傻说不上爱别说谎就一点喜欢 说不上恨别纠缠别装作感叹 </div> <script> function keyLight(id, key, bgColor){ var oDiv = document.getElementById(id), sText = oDiv.innerHTML, bgColor = bgColor || "orange", sKey = "<span name='addSpan' style='background-color: "+bgColor+";'>"+key+"</span>", num = -1, rStr = new RegExp(key, "g"), rHtml = new RegExp("\<.*?\>","ig"), //匹配html元素 aHtml = sText.match(rHtml); //存放html元素的数组 sText = sText.replace(rHtml, '{~}'); //替换html标签 sText = sText.replace(rStr,sKey); //替换key sText = sText.replace(/{~}/g,function(){ //恢复html标签 num++; return aHtml[num]; }); oDiv.innerHTML = sText; } function search(){ if(typeof($("span[name='addSpan']").get(0)) != 'undefined'){ var html = $("span[name='addSpan']").get(0).textContent; $("span[name='addSpan']").before(html); $("span[name='addSpan']").remove(); } //location.reload(); var key = document.getElementById("key").value; if($.trim(key) != null && $.trim(key) != ''){ keyLight('result', key); } } </script> </body> </html>