JS高亮显示搜索关键字

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>highLight</title>
</head>
</head>
<body>
  <p>
    滚滚长江东逝水,浪花淘尽英雄。是非成败转头空。青山依旧在,几度夕阳红。白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢。古今多少事,都付笑谈中。
  </p>
  <div>
      <input type="text" placeholder="input key words"/>                         
      <button>submit</button>
  </div>
  <script type="text/javascript">
    const content = document.getElementsByTagName(p)[0];
    const text = content.innerHTML;
    const value = document.getElementsByTagName(input)[0];
    const button = document.getElementsByTagName(button)[0];
    button.onclick = () => {
      const keyWords = value.value;
      const cut = text.split(keyWords);
      content.innerHTML = cut.join(<span style="color:red;"> + keyWords + </span>);
    };
  </script>
</body>
</html>
经验分享 程序员 微信小程序 职场和发展