返回
Js特效案例--百度搜索框特效展示
前端
2023-11-14 17:38:38
在前端开发中,Js 特效可以为网站增添许多乐趣。本文将介绍一个 Js 特效案例--百度搜索框的展示。该特效可以为网站增加美感,让用户在搜索时有更好的体验。
HTML布局
实现设计好相关需要的区域,html布局如下:
- 搜索区域:包含搜索框和搜索按钮
- 搜索结果匹配区域
<div id="search">
<input type="text" placeholder="搜索" id="search-input">
<button type="submit" id="search-button">搜索</button>
</div>
<div id="search-results"></div>
CSS样式
接下来,我们需要为搜索框和搜索按钮添加一些 CSS 样式。
#search {
width: 300px;
margin: 0 auto;
}
#search-input {
width: 200px;
height: 30px;
padding: 5px;
border: 1px solid #ccc;
}
#search-button {
width: 80px;
height: 30px;
background-color: #000;
color: #fff;
border: 1px solid #ccc;
}
Js代码
最后,我们需要编写 Js 代码来实现特效。
// 获取搜索框和搜索按钮元素
const searchInput = document.getElementById('search-input');
const searchButton = document.getElementById('search-button');
// 监听搜索按钮的点击事件
searchButton.addEventListener('click', () => {
// 获取搜索框中的内容
const searchQuery = searchInput.value;
// 使用 Ajax 请求发送搜索查询到服务器
const xhr = new XMLHttpRequest();
xhr.open('GET', `search.php?q=${searchQuery}`);
xhr.onload = () => {
// 将搜索结果显示在搜索结果匹配区域
const searchResults = document.getElementById('search-results');
searchResults.innerHTML = xhr.responseText;
};
xhr.send();
});
总结
通过上述步骤,我们就完成了 Js 特效案例--百度搜索框的展示。该特效可以为网站增加美感,让用户在搜索时有更好的体验。