<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>js关键字高亮显示</title> </head> <body> <input type="text" id="text" placeholder="请输入关键字"/> <input type="button" id="button" value="确定"/> <br /> <br /> <div id="content"> 你好呀! </div> <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); //使用js中array的join方法,将带有样式的关键字作为拼接数组中所有元素 content.innerHTML = values.join('<span style="background:green;">' + value + '</span>'); }; </script> </body> </html>