// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>测试 - layui</title>
<link rel="stylesheet" href="layui/css/layui.css">
<link rel="stylesheet" href="myInput.css">
</head>
<body>
<div class="myInput" style="width: 200px;">
<input type="text">
</div>
<div class="myInput" style="width: 200px;">
<input type="text">
</div>
<script src="jquery-1.11.3.min.js"></script>
<script src="layui/layui.js"></script>
<script src="myInput.js"></script>
</body>
</html>
// myInput.css
.myInput {
position: relative;
}
.myInput input {
display: block;
width: 100%;
padding-left: 10px;
height: 38px;
line-height: 1.3;
line-height: 38px\9;
border-width: 1px;
border-style: solid;
background-color: #fff;
color: rgba(0, 0, 0, .85);
border-radius: 2px;
border-color: #eee;
}
.myInput .closeIcon {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
color: #999;
font-size: 16px;
display: none;
}
.myInput.hoverIn .closeIcon {
display: block;
}
// myInput
(function() {
$('.myInput').append('<i class="layui-icon layui-icon-close-fill closeIcon"></i>')
$('.myInput .closeIcon').click(function() {
$(this).siblings('input').val('')
})
$('.myInput').hover(function() {
if ($(this).find('input').val().length) {
$(this).find('.closeIcon').fadeIn();
}
}, function() {
$(this).removeClass('hoverIn')
$(this).find('.closeIcon').hide();
});
$('.myInput input').on("input", function() {
if ($(this).val().length) {
$(this).siblings('.closeIcon').fadeIn();
} else {
$(this).siblings('.closeIcon').hide();
}
});
})()