1.结果展示(需要用到bootstrap,jquery)
2.HTML代码
<div class="container">
<form class="form-signin" autocomplete="off">
<h2 class="form-signin-heading text-primary text-center">登录</h2>
<span class="text-muted">请输入用户名和密码</span>
<!-- 将需要用到清除按钮的输入框放到 'input-group-clear' 的div中,添加一个 'input-clear' 的span -->
<div class="input-group-clear" style="position:relative">
<label for="user-name" class="sr-only">用户名</label>
<input type="text" id="username" class="form-control" placeholder="用户名" required autofocus>
<span class="input-clear isfocus">
×
</span>
</div>
<div class="input-group-clear" style="position:relative">
<label for="password" class="sr-only">密码</label>
<input type="password" id="password" class="form-control" placeholder="密码" required>
<span class="input-clear">
×
</span>
</div>
<button class="btn btn-lg btn-primary btn-block" type="button" id="login-btn">登录</button>
</form>
</div>
3.CSS代码
.input-clear {
display: none;
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
z-index: 111;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000;
text-shadow: 0 1px 0 #fff;
filter: alpha(opacity=20);
opacity: .2;
cursor: pointer;
}
4.JS代码
// 输入框清除
$(function () {
// 监听输入框内容变动
$(".input-group-clear").bind("input propertychange", function () {
// 获取输入框的值
var inputValue = $(this).children('input').val();
// 判断输入框是否有值
if (inputValue >= 1) {
// 显示清除
$(this).children('.input-clear').show();
} else {
// 隐藏清除
$(this).children('.input-clear').hide();
}
});
// 输入框获取焦点事件,判断输入框是否有值,有值则显示清除
$(".input-group-clear").children('input').focus(function () {
var inputValue = this.value.length;
if (inputValue >= 1) {
$(this).siblings('.input-clear').show();
}
});
// 点击清除事件
$('.input-clear').click(function () {
// 清空输入框值
$(this).siblings('input').val('');
// 隐藏清除
$(this).hide();
});
// 离开输入框div事件,隐藏清除,此处不能使用blur,因为blur只对输入框有效
$(".input-group-clear").focusout(function () {
var igc = $(this);
// 设置一个定时器,离开输入框div,200毫秒后隐藏清除,不设置定时器会出现点击清除无效的情况
setTimeout(function () {
igc.children('.input-clear').hide();
}, 200)
});
})