[英]How to highlight text when entering into input search bar
function myFunction() { // Declare variables var input, filter, ul, li, a, i, txtValue; input = document.getElementById('myInput'); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName('li'); // Loop through all list items, and hide those who don't match the search query for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; li[i].style.color = 'green'; } else { li[i].style.display = "none"; } } }
body{ margin: 0; }.center{ margin-left:auto; margin-right: auto; width: 1200px; } nav { height: 80px; background: #9bcfe0; display: flex; justify-content: space-between; align-items: center; }.logo { color: white; border-radius: .5; font-size: 1.5rem; font-weight: bold; font-style: italic; padding: .5rem 2rem; margin-left: 10px; border-radius: 25px; background-color: #e76f3d; } nav a { text-decoration: none; color: #000; padding: 0 1.5rem; } nav a:hover { color: #fff; background-color: #e76f3d; }.nav-items{ font-weight: bold; margin-right: 10px; }.Main-Items{ display: flex; justify-content: space-around; margin-left:20%; margin-right:20%; padding-top: 10px; margin-bottom: 20px; font-size: 20px; }.Main-Items a{ text-decoration: none; color: #1167b1; padding-right: 10px; margin-left:10px; }.Main-Items a:hover{ color: white; background: #e76f3d; } /***Search bar***/ #myInput { background-image: url('/css/searchicon.png'); /* Add a search icon to input */ background-position: 10px 12px; /* Position the search icon */ background-repeat: no-repeat; /* Do not repeat the icon image */ margin-left:10%; width: 74%; font-size: 16px; /* Increase font-size */ padding: 12px 20px 12px 40px; /* Add some padding */ border: 1px solid #ddd; /* Add a grey border */ margin-bottom: 12px; /* Add some space below the input */ } #myUL { /* Remove default list styling */ list-style-type: none; padding: 0; margin: 0; margin-left: 10%; margin-right: 10%; } #myUL li a { /*** border: 1px solid #ddd; /* Add a border to all links */ margin-top: -1px; /* Prevent double borders */ background-color: white; /* Grey background color */ padding: 15px; /* Add some padding */ text-decoration: none; /* Remove default text underline */ font-size: 20px; /* Increase the font-size */ color: #1167b1; /* Add a black text color */ display: block; /* Make it into a block element to fill the whole list */ } #myUL li a:hover:not(.header) { background-color: #eee; /* Add a hover effect to all links, except for headers */ } /*** @media screen and (max-width: 768px) {.hero-container { grid-template-columns: 1fr; } } ***/
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="Styles1.css"> </head> <body> <script src="scripts:js"></script> <div class="center"> <nav> <div class="logo">Nexamp</div> <div class="nav-items"> <a href="/">Home</a> <a href="/">About</a> <a href="/">Contact</a> </div> </nav> <div class = "Main-Items"> <strong>Collections.</strong> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> </div> <section class="search"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <ul id="myUL"> <li><a href="#">Community Solar</a></li> <li><a href="#">Organic</a></li> <li><a href="#">Company Organization</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul> </section> </div> </body> </html>
沒有條目的搜索欄 有條目的搜索欄 在上圖中,我有一個允許輸入的搜索欄,並在輸入后進行過濾。 但是,我想 go 更進一步,並在輸入時為文本添加高亮顯示。 在此示例中,對於圖片 2,我希望為所選內容突出顯示文本。 這是我當前的代碼。
實際上,我沒有分析您的整個代碼。 但我做了你想要的一部分。 我假設你可以整合這些。 這里:
function onInput(input) { highlight(input, document.querySelector('#target-text')) } function highlight(input, target) { const value = input.value const matches = findText(target.textContent, input.value) unwrap(target) matches.forEach(match => target.innerHTML = wrap(target.textContent, match[0], match[1])) } function findText(string, search) { const matches = [] let i = -1 let ind = 0 do { i = string.indexOf(search, i + 1) if (i > -1) matches.push([i, i + search.length]) } while (i > -1 && search) return matches } function wrap(text, from, to) { if ((from.== 0 && from < 1) ||,to) return text return `${text.slice(0, from)}<span class="highlight">${text.slice(from, to)}</span>${text.slice(to. text.length)}` } function unwrap(wrapper) { return Array.from(wrapper.querySelectorAll('.highlight')).forEach(target => target.replaceWith(target.textContent)) }
.highlight { color: green; }
<input id="search-input" oninput="onInput(this)"/> <div id="target-text">search text</div>
您可以使用String.prototype.slice替換每個鏈接的文本並使用匹配的字符創建一個跨度。
function myFunction() { // Declare variables var input, filter, ul, li, a, i, txtValue; input = document.getElementById('myInput'); filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName('li'); // Loop through all list items, and hide those who don't match the search query for (i = 0; i < li.length; i++) { a = li[i].getElementsByTagName("a")[0]; txtValue = a.textContent || a.innerText; let matchStart; if ((matchStart = txtValue.toUpperCase().indexOf(filter)) > -1) { // Replace link text to include highlighted span a.innerHTML = ''; a.appendChild(document.createTextNode(txtValue.slice(0, matchStart))); const highlighted = document.createElement('span'); highlighted.classList.add('highlighted'); highlighted.innerText = txtValue.slice(matchStart, matchStart + filter.length); a.appendChild(highlighted); a.appendChild(document.createTextNode(txtValue.slice(matchStart + filter.length))); li[i].style.display = ""; li[i].style.color = 'green'; } else { li[i].style.display = "none"; } } }
body{ margin: 0; }.center{ margin-left:auto; margin-right: auto; width: 1200px; } nav { height: 80px; background: #9bcfe0; display: flex; justify-content: space-between; align-items: center; }.logo { color: white; border-radius: .5; font-size: 1.5rem; font-weight: bold; font-style: italic; padding: .5rem 2rem; margin-left: 10px; border-radius: 25px; background-color: #e76f3d; } nav a { text-decoration: none; color: #000; padding: 0 1.5rem; } nav a:hover { color: #fff; background-color: #e76f3d; }.nav-items{ font-weight: bold; margin-right: 10px; }.Main-Items{ display: flex; justify-content: space-around; margin-left:20%; margin-right:20%; padding-top: 10px; margin-bottom: 20px; font-size: 20px; }.Main-Items a{ text-decoration: none; color: #1167b1; padding-right: 10px; margin-left:10px; }.Main-Items a:hover{ color: white; background: #e76f3d; } /***Search bar***/ #myInput { background-image: url('/css/searchicon.png'); /* Add a search icon to input */ background-position: 10px 12px; /* Position the search icon */ background-repeat: no-repeat; /* Do not repeat the icon image */ margin-left:10%; width: 74%; font-size: 16px; /* Increase font-size */ padding: 12px 20px 12px 40px; /* Add some padding */ border: 1px solid #ddd; /* Add a grey border */ margin-bottom: 12px; /* Add some space below the input */ } #myUL { /* Remove default list styling */ list-style-type: none; padding: 0; margin: 0; margin-left: 10%; margin-right: 10%; } #myUL li a { /*** border: 1px solid #ddd; /* Add a border to all links */ margin-top: -1px; /* Prevent double borders */ background-color: white; /* Grey background color */ padding: 15px; /* Add some padding */ text-decoration: none; /* Remove default text underline */ font-size: 20px; /* Increase the font-size */ color: #1167b1; /* Add a black text color */ display: block; /* Make it into a block element to fill the whole list */ } #myUL li a:hover:not(.header) { background-color: #eee; /* Add a hover effect to all links, except for headers */ } #myUL li a.highlighted { background-color: yellow; } /*** @media screen and (max-width: 768px) {.hero-container { grid-template-columns: 1fr; } } ***/
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="Styles1.css"> </head> <body> <script src="scripts:js"></script> <div class="center"> <nav> <div class="logo">Nexamp</div> <div class="nav-items"> <a href="/">Home</a> <a href="/">About</a> <a href="/">Contact</a> </div> </nav> <div class = "Main-Items"> <strong>Collections.</strong> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> <a href=espn.com>Animations</a> </div> <section class="search"> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <ul id="myUL"> <li><a href="#">Community Solar</a></li> <li><a href="#">Organic</a></li> <li><a href="#">Company Organization</a></li> <li><a href="#">Bob</a></li> <li><a href="#">Calvin</a></li> <li><a href="#">Christina</a></li> <li><a href="#">Cindy</a></li> </ul> </section> </div> </body> </html>
function myFunction() {
const inputValue = document.getElementById("myInput").value;
const listItems = document.querySelector("#myUL").querySelectorAll("li");
if (!inputValue) {
listItems.forEach((li) => (li.querySelector("a").style.color = "#1167b1"));
return;
}
listItems.forEach((li) => {
const child = li.querySelector("a");
const txtValue = child.innerText;
child.style.color =txtValue.toUpperCase().indexOf(inputValue.toUpperCase()) > -1
? "green"
: "#1167b1";
});
}
只需替換它,一切都會完美無缺。
這是一個簡單的文本高亮解決方案https://codepen.io/mkorostoff/pen/abLBOqd 。 您可以將其插入您的 onkeyup function。 您可能還喜歡https://github.com/este/highlight-text ,它做同樣的事情,但不區分大小寫。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">.highlight {background-color: lightblue;}</style>
<title></title>
</head>
<body>
<div><strong>Search term: </strong>cat</div>
<div class="search-result">cat</div>
<div class="search-result">catthew</div>
<div class="search-result">cathy</div>
<div class="search-result">calgury</div>
<div class="search-result">camel</div>
<div class="search-result">doja cat</div>
<div class="search-result">uncatagorized</div>
<script>
let searchTerm = 'cat';
let highlight = `<span class="highlight">${searchTerm}</span>`;
let searchResults = document.querySelectorAll('.search-result');
searchResults.forEach((searchResult) => {
let text = searchResult.innerHTML;
if (text === searchTerm) {
text = highlight;
}
else {
let parts = text.split(searchTerm);
let newParts = [];
parts.forEach((part) => {
if (part === '') {
newParts.push(`<span class="highlight">${searchTerm}</span>`)
}
else newParts.push(part);
});
text = newParts.join('');
}
searchResult.innerHTML = text;
})
</script>
</body>
</html>
使用 Plain Vanilla 的簡短而簡單的解決方案 JavaScript
const searchHighlighter = (elem, that) => { let el = document.querySelector(elem) el.innerHTML = el.innerText.replace( new RegExp( that.value + '(??([^<]+),<)', 'gi'); '<mark>$&</mark>' ); return el }
<input id="searchInput" onkeyup="searchHighlighter('#content', this)" placeholder="Type here" /> <div id="content"> Type in input and see the result! Now type TYPE word to see multi highlight of same word </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.