Home > Web Front-end > JS Tutorial > body text

JS code to implement static page search and highlighting

小云云
Release: 2018-02-05 15:50:07
Original
2083 people have browsed it

This article mainly introduces JS to implement static page search and highlighting functions, involving javascript event response, character traversal replacement and dynamic transformation of page element attributes and other related operating techniques. Friends who need it can refer to it. I hope it can help everyone. .


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS搜索</title>
</head>
<body>
<input id="key-word" class="key-word" value="请输入搜索内容" />
<button id="search-button">搜索</button>
<p id="content" >
<p>这是主体内容,有很多内容,很多很多啊啊啊……,比如1234abcd啊啊啊啊</p>
<p>这是主体内容,有很多内容,很多很多啊啊啊……,比如1234abcd啊啊啊啊</p>
<p>这是主体内容,有很多内容,很多很多啊啊啊……,比如1234abcd啊啊啊啊</p>
<p>这是主体内容,有很多内容,很多很多啊啊啊……,比如1234abcd啊啊< d d>啊啊</p>
</p>
<script>
function $(id){
return document.getElementById(id)
}
var putWordsObj = $(&#39;key-word&#39;);
putWordsObj.onfocus = function(){
if(this.value == &#39;请输入搜索内容&#39;)this.value=&#39;&#39;;
}
putWordsObj.onblur = function(){
if(!this.value)this.value=&#39;请输入搜索内容&#39;;
}
//search
$(&#39;search-button&#39;).onclick = function(){
var content = $(&#39;content&#39;).innerHTML;
var keyWord = $(&#39;key-word&#39;).value;
content = search_do(content, keyWord);
$(&#39;content&#39;).innerHTML = content;
//alert(content)
}
function search_do(content,keyWord){
var keyWordArr = keyWord.replace(/[\s]+/g,&#39; &#39;).split(&#39; &#39;);
var re;
for(var n = 0; n < keyWordArr.length; n ++) {
//re = new RegExp(">[\s\S]*?"+keyWordArr[n]+"[\s\S]*?<\S","gmi");
re = new RegExp(""+keyWordArr[n]+"","gmi");
content = content.replace(re,&#39;<span style="color:#0f0;background-color:#ff0">&#39;+keyWordArr[n]+&#39;</span>&#39;);
}
return content;
}
</script>
</body>
</html>
Copy after login

The running effect is as follows:

Related recommendations:

JavaScript implementation Search and highlighting function examples

jQuery Json highlighting plug-in json-viewer.js usage detailed explanation

JavaScript replace implementation search key Word highlighting method


#

The above is the detailed content of JS code to implement static page search and highlighting. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template