要在网站中添加一个搜索功能,可以使用HTML5的内置标签,比如<input type="search">
,结合CSS和JavaScript实现。
首先,需要在HTML文件中放置一个搜索框的代码,例如:
<form>
<label for="search">Search:</label>
<input type="search" id="search" name="search">
<button type="submit">Go</button>
</form>
然后,使用CSS进行样式设置。最常见的是把搜索框定位在网站顶部,并设置宽度和字体大小等属性。
form {
position: fixed;
top: 0;
right: 0;
left: 0;
height: 50px;
background-color: #fff;
z-index: 9999;
}
input[type="search"] {
font-size: 16px;
border: none;
width: 70%;
padding: 10px;
}
button[type="submit"] {
background-color: #0077cc;
color: #fff;
font-size: 16px;
border: none;
padding: 10px 20px;
}
最后,使用JavaScript对搜索框的输入内容进行监听,并对匹配到的关键词进行高亮颜色设置。
// 获取DOM元素
var searchInput = document.getElementById("search");
var pageContent = document.getElementById("page-content");
// 监听输入
searchInput.addEventListener("input", function() {
// 获取搜索框输入内容
var searchTerm = searchInput.value.toLowerCase();
// 清除之前的高亮
pageContent.innerHTML = pageContent.innerHTML.replace(/<mark>/g, "").replace(/<\/mark>/g, "");
// 如果搜索框不为空,则对匹配到的关键词进行高亮
if(searchTerm !== "") {
pageContent.innerHTML = pageContent.innerHTML.replace(new RegExp(searchTerm, "gi"), function(match) {
return "<mark>" + match + "</mark>";
});
}
});
上述代码中,使用<mark>
标签对匹配到的关键词进行了高亮处理。
需要注意的是,为了达到更好的用户体验和搜索准确度,可以根据需求对搜索功能进行进一步优化,如添加自动补全功能、设置最小输入字符数等。