bootstrap4写一个百度搜索框,增加防抖,输入框增加 X 清除功能,点击搜索必须要等待请求结果返回后才能继续点击,样式居中显示
时间: 2023-08-22 17:08:27 浏览: 245
Bootstrap实现弹性搜索框
下面是使用Bootstrap 4编写的百度搜索框代码,包括防抖和清除功能,同时也增加了点击搜索时等待请求结果返回的功能,并且样式居中显示:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bootstrap 4百度搜索框</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css">
<style>
/* 居中显示 */
.search-box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
/* 清除按钮 */
.search-box .search-input::-ms-clear {
display: none;
}
.search-box .search-input::-ms-reveal {
display: none;
}
.search-box .search-input::-webkit-search-cancel-button {
position: relative;
right: -10px;
opacity: 0.5;
}
.search-box .search-input::-moz-placeholder {
color: #ddd;
opacity: 1;
}
.search-box .search-input:-moz-placeholder {
color: #ddd;
opacity: 1;
}
.search-box .search-input::-webkit-input-placeholder {
color: #ddd;
opacity: 1;
}
/* 加载动画 */
.search-box .loading {
margin-left: 5px;
display: none;
}
.search-box .loading.active {
display: inline-block;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3 search-box">
<form>
<div class="input-group">
<input type="text" class="form-control search-input" placeholder="请输入搜索内容">
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-search"></i>
</span>
<span class="input-group-text btn-clear">
<i class="fa fa-times"></i>
</span>
<span class="input-group-text loading">
<i class="fa fa-spinner fa-spin"></i>
</span>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
// 防抖
var timer = null;
$('.search-input').on('input', function() {
clearTimeout(timer);
var self = $(this);
timer = setTimeout(function() {
if (self.val() == '') {
$('.btn-clear').hide();
} else {
$('.btn-clear').show();
}
}, 500);
});
// 清除按钮
$('.btn-clear').on('click', function() {
$('.search-input').val('').focus();
$(this).hide();
});
// 搜索按钮
$('.input-group-text:not(.loading)').on('click', function() {
var self = $(this);
var input = self.parent().siblings('.search-input');
var loading = self.parent().find('.loading');
var keyword = input.val().trim();
if (keyword == '') {
input.focus();
return;
}
loading.addClass('active');
// 模拟请求
setTimeout(function() {
loading.removeClass('active');
input.val('');
$('.btn-clear').hide();
input.focus();
alert('搜索成功');
}, 1500);
});
});
</script>
</body>
</html>
```
在上述代码中,使用了Bootstrap 4中的input-group、form-control、input-group-text等样式类,通过jQuery实现了防抖、清除和搜索功能,并且增加了加载动画。同时,为了实现样式居中显示,使用了display: flex和justify-content: center样式。
阅读全文