Ajax&JavaScript&css模仿百度一下模糊查询功能
以下是一个简单的使用JavaScript、Ajax和CSS来模拟百度下拉搜索框的模糊查询功能的示例代码。
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模糊查询示例</title>
<style>
#search-box {
position: relative;
}
#search-suggestions {
display: none;
position: absolute;
top: 100%;
left: 0;
z-index: 1;
background-color: #f9f9f9;
border: 1px solid #cacaca;
border-radius: 4px;
overflow: auto;
}
#search-suggestions a {
display: block;
padding: 6px 12px;
text-decoration: none;
color: #333;
}
#search-suggestions a:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="search-box">
<input type="text" id="search-input" onkeyup="getSuggestions()">
<div id="search-suggestions">
<!-- 下拉搜索建议由JavaScript动态填充 -->
</div>
</div>
<script>
function getSuggestions() {
var input = document.getElementById('search-input').value;
if (input.length === 0) {
document.getElementById('search-suggestions').innerHTML = '';
document.getElementById('search-suggestions').style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var suggestions = JSON.parse(xhr.responseText);
if (suggestions.length > 0) {
document.getElementById('search-suggestions').innerHTML = suggestions.map(function(suggestion) {
return '<a href="/search?q=' + encodeURIComponent(suggestion) + '">' + suggestion + '</a>';
}).join('');
document.getElementById('search-suggestions').style.display = 'block';
} else {
document.getElementById('search-suggestions').innerHTML = '';
document.getElementById('search-suggestions').style.display = 'none';
}
}
};
xhr.open('GET', '/api/search-suggestions?q=' + encodeURIComponent(input), true);
xhr.send();
}
</script>
</body>
</html>
假设有一个后端API /api/search-suggestions
可以根据输入的搜索词返回相应的建议列表。
当用户在搜索框中输入文字时,getSuggestions
函数会通过Ajax请求后端接口,获取到相应的搜索建议后更新下拉列表。
注意:这个示例没有实现全部功能,仅提供了搜索建议的获取和展示方法,并且假设了一个后端API
评论已关闭