如何在输入 html 时突出显示文本?

How to highlight text while typing in html?

我有搜索项目名称和项目 ID 的搜索框,它在边栏中被过滤。

我可以搜索和过滤在搜索框中输入的文本,但无法突出显示已搜索的文本。

Here is the html, css and javascript code which i have tried so far:

搜索框html代码

      var filterInput, ul, li, a, i;

    filterInput = document.getElementById('filterInput');
    // Add event listener
    filterInput.addEventListener('keyup', filterNames);
     function filterNames(){
      // Get value of input
      let filterValue = document.getElementById('filterInput').value.toUpperCase();

     // Get names ul
      let ul = document.getElementById('projectlist');
 
     // Get lis from ul.
     let li = ul.querySelectorAll('li.nav-item');

     // Loop through collection-item list
      for(let i = 0;i < li.length;i++){
       let a = li[i].getElementsByTagName('a')[0];
       // If matched
       if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
        li[i].style.display = '';
        var text=a.innerHTML;
        text = text.replace( filterValue, '<span class="search-found">' + 
     filterValue + '</span>' );
        a.innerHTML=text;
        
      } else {
       li[i].style.display = 'none';
      
      }
     }
     }
  .sidebar .nav-link .highlight {

    background-color: #7b9d6f;
 
    }
  <input id="filterInput" class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">

Here is the project list html code:

      <div id="projectlist" class="sidebar-sticky" >
    <ul class="nav flex-column nav-pills">
     
      <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
          Project 1
          <div>
            <small>
            ProjectId: 1
          </small>
          </div>
        </a>
        </li>
         <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
          Project 2
          <div>
            <small>
            ProjectId: 2
          </small>
          </div>
        </a>
        </li>
         <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
          Project 3
          <div>
            <small>
            ProjectId: 3
          </small>
          </div>
        </a>
        </li>
        
      </ul>
    </div>





  
 
     

请帮我高亮代码

请在该标签中添加class并为此添加css 喜欢

if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
        li[i].style.display = '';
        var text=a.textContent;
        text = text.replace( filterValue, '<span class="search-found">' + 
     filterValue + '</span>' );
        a.textContent=text;
         a.classList.add('bold-class');
      } else {
       li[i].style.display = 'none';

      }

时尚

.bold-class{
 font-weight:bold
}

正如我在你的代码中看到的那样,你添加了 spanclass="search-found" 但是 你的 css 不同 class .highlight 不存在
改变你的 css:

.search-found {

    background-color: red;

    }

  var filterInput, ul, li, a, i;

    filterInput = document.getElementById('filterInput');
    // Add event listener
    filterInput.addEventListener('keyup', filterNames);
     function filterNames(){
      // Get value of input
      let filterValue = document.getElementById('filterInput').value.toUpperCase();

     // Get names ul
      let ul = document.getElementById('projectlist');
 
     // Get lis from ul.
     let li = ul.querySelectorAll('li.nav-item');

     // Loop through collection-item list
      for(let i = 0;i < li.length;i++){
       let a = li[i].getElementsByTagName('a')[0];
       // If matched
       if(a.innerHTML.toUpperCase().indexOf(filterValue) > -1){
        li[i].style.display = '';
        var text=a.innerHTML;
        text = text.replace( filterValue, '<span class="search-found">' + 
     filterValue + '</span>' );
        a.innerHTML=text;
        
      } else {
       li[i].style.display = 'none';
      
      }
     }
     }
.search-found {

    background-color: red;
 
    }
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<input id="filterInput" class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">



      <div id="projectlist" class="sidebar-sticky" >
    <ul class="nav flex-column nav-pills">
     
      <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%" >
          Project 1
          <div>
            <small>
            ProjectId: 1
          </small>
          </div>
        </a>
        </li>
         <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%" >
          Project 2
          <div>
            <small>
            ProjectId: 2
          </small>
          </div>
        </a>
        </li>
         <li class="nav-item" >
        <a name="{{.ProjectID}}" class="nav-link" href="#">
          <img class="img-fluid" style="width:8%">
          Project 3
          <div>
            <small>
            ProjectId: 3
          </small>
          </div>
        </a>
        </li>
        
      </ul>
    </div>

我在类似的项目中使用了 hilitor,效果很好。使用纯 JavaScript.

的简单开源构建

这是你的例子。我稍微改变了你的结构:

// Get input element
let filterInput = document.getElementById('filterInput');
// Add event listener
filterInput.addEventListener('keyup', filterNames);

function filterNames() {
    // Get value of input
    let filterValue = document.getElementById('filterInput').value.toUpperCase();

    // Get names ul
    let ul = document.getElementById('projectlist');
    // Get lis from ul
    let li = ul.querySelectorAll('li.nav-item');

    // Loop through collection-item lis
    for(let i = 0;i < li.length;i++) {
       let a = li[i].getElementsByTagName('p')[0];

        // If matched
        if(a.textContent.toUpperCase().indexOf(filterValue) > -1) {
         li[i].style.display = '';
        } else {
         li[i].style.display = 'none';
        }
    }
}

// Call Hilitor
var myHilitor2;
document.addEventListener("DOMContentLoaded", function(e) {
 // Set the parent
 myHilitor2 = new Hilitor("nav-item");
 // Text direction
 myHilitor2.setMatchType("left");
}, false);

// Event
document.getElementById("filterInput").addEventListener("keyup", function(e) {
 myHilitor2.apply(this.value);
}, false);
<script src="https://rawgit.com/GerHobbelt/hilitor/master/hilitor.js"></script>

<div id="projectlist" class="sidebar-sticky" >

 <input id="filterInput" class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">

 <ul class="nav flex-column nav-pills">
  <li class="nav-item" >
   <a name="{{.ProjectID}}" class="nav-link" href="#">
    <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
    <p class="inner">Project 1</p>
   </a>
  </li>
  <li class="nav-item" >
   <a name="{{.ProjectID}}" class="nav-link" href="#">
    <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
    <p class="inner">Project 2</p>
   </a>
  </li>
  <li class="nav-item" >
   <a name="{{.ProjectID}}" class="nav-link" href="#">
    <img class="img-fluid" style="width:8%" src="../static/image/generic_gcp.png">
    <p class="inner">Project 3</p>
   </a>
  </li>
 </ul>
</div>

这是source code and you can learn more about its options in the documentation

在这里你可以找到一个工作示例 https://codepen.io/silabhijit/pen/bMvXgm

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=0, width=device-width, height=device-height, viewport-fit=cover">
    <title>Highlight Text while typeing in input box</title>
    <style>
        body {
            font-family: verdana;
        }

        .page-content {
            width: 100%;
            max-width: 990px;
            margin: 0 auto;
        }

        input {
            padding: 10px;
            width: 350px;
            border-radius: 5px;
            border: 1px solid #aaa;
        }

        ul {
            list-style: none;
            padding: 0;
            margin: 15px 0 0 0;
        }
        ul li {
            border: 1px solid #aaa;
            padding: 10px;
            border-bottom: 0;
        }

        ul li:last-child {
            border-bottom: 1px solid #aaa;;
        }

        ul li strong {
            color: #ff0000;
        }
    </style>
</head>
    <body>
        <header class="page-header">
        </header>
        <main class="page-content">
            <div class="input-holder">
                <input type="text" class="model" />
            </div>
            <ul>
                <li>Abhijit Sil</li>
                <li>Abhishek Roy</li>
                <li>Abhi Sen</li>
                <li>Ranjit Sharma</li>
                <li>Ravi Kar</li>
                <li>Surojit Shil</li>
                <li>Arunayan Shil</li>
            </ul>
        </main>
        <footer class="page-footer">
        </footer>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('.model').on('keyup', function() {
                    var val = $(this).val();

                    var listItems = $('ul li');
                    listItems.each(function() {
                        var itemVal = $(this).text();

//                        remove strong tag from original string
                        itemVal = itemVal.replace('<strong>', '');
                        itemVal = itemVal.replace('</strong>', '');

                        if(itemVal.indexOf(val) !== -1) {
                            var convertedString = "<strong>" + val + "</strong>"
                            var output = itemVal.replace(val, convertedString);
                            $(this).html(output);
                        } else {
                            $(this).html(itemVal);
                        }

                    })
                })
            });

        </script>
    </body>
</html>