如何用 javascript 实现html页面的关键字搜索?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
</head>
<body>

<input type="text">
<div data-v-4fced2a0="" class="markdown-body">
  <section data-v-4fced2a0=""><h1 id="Hello">Hello</h1>
    <h2>hello1</h2>
    <h2>hello2</h2>
    <p><code>&lt;span&gt;<span>{{</span>sss<span>}}</span>&lt;/span&gt;</code></p>
    <blockquote><p>This is test.</p></blockquote>
    <ul>
      <li>How are you?</li>
      <li>Fine, Thank you, and you?</li>
      <li>I'm fine, too. Thank you.</li>
      <li>
        ??????????????????????????????????????????????????????????????????????????????
      </li>
    </ul>
    <h1 id="最新消息">最新消息</h1>
  </section>
</div>

<script>
  (function () {

    var input = document.getElementsByTagName('input')[0]
    var origin = document.getElementsByClassName('markdown-body')[0].innerHTML;

    input.addEventListener('keyup', function () {
      var searchKey = input.value
      console.log('keyup', searchKey)
      
      document.getElementsByClassName('markdown-body')[0].innerHTML =
        origin.replace(searchKey, '<span class=\'highlight\'>' + searchKey + '</span>')
    })


  }())
</script>
</body>
</html>

如何搜索markdown-body中的关键字,又不对html结构造成影响呢?类似浏览器的搜索功能

阅读 10.1k
2 个回答
document.getElementsByClassName('markdown-body')[0].innerHTML=html.replace(searchKey, '<span class=\'highlight\'>' + searchKey + '</span>')

demo

浏览器搜索框都不在可视区范围内,应该是个插件。你js写的话肯定是会改变结构的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏