html+css+js实现简单的搜索关键词标记为红色

这篇文章介绍了一个使用JavaScript实现的简单搜索功能,用户输入关键词后,会在列表中高亮显示包含该关键词的文本示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>搜索页</title>
<style>
  body {
    font-family: Arial, sans-serif;
  }
  #search-container {
    text-align: center;
    padding: 20px;
  }
  #search-input {
    width: 300px;
    padding: 5px;
  }
  #results-container {
    margin-top: 20px;
  }
  .highlight {
    color: red;
    font-weight: bold;
  }
</style>
</head>
<body>
  <div id="search-container">
    <input type="text" id="search-input" placeholder="请输入关键词">
    <button onclick="search()">搜索</button>
  </div>
  <div id="results-container">
    <ul id="results-list"></ul>
  </div>

  <script>
    function search() {
      const searchInput = document.getElementById('search-input');
      const searchTerm = searchInput.value.toLowerCase();
      const resultsList = document.getElementById('results-list');
      resultsList.innerHTML = '';

      // 在这里替换为你的数据,以下为示例数据
      const data = [
        '这是一个示例句子。',
        '在这个例子中,关键词会被标记。',
        '你可以根据需要替换这些数据。',
        '示例搜索功能使用JavaScript实现。',
        '关键词可以是用户在搜索框中输入的内容。',
        '记得根据你的实际需求进行修改。'
      ];

      data.forEach(item => {
        const lowerCaseItem = item.toLowerCase();
        if (lowerCaseItem.includes(searchTerm)) {
          const highlightedItem = item.replace(new RegExp(searchTerm, 'gi'), match => `<span class="highlight">${match}</span>`);
          const li = document.createElement('li');
          li.innerHTML = highlightedItem;
          resultsList.appendChild(li);
        }
      });
    }
  </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值