<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 190px;
height: 30px;
line-height: 30px;
border: 1px solid #ededed;
padding: 0 5px;
display: none;
font-size: 16px;
position: absolute;
top: 10px;
}
input[type="text"] {
width: 200px;
margin-top: 40px;
}
</style>
</head>
<body>
<div class="box"></div>
<input type="text">
<script>
var ipt = document.querySelector('input');
var box = document.querySelector('.box');
ipt.addEventListener('keyup', function() {
if (this.value == "") {
box.style.display = 'none';
} else {
box.style.display = 'block';
box.innerHTML = this.value;
}
});
//当失去焦点,隐藏box盒子
ipt.addEventListener('blur', function() {
box.style.display = 'none';
});
//当获取焦点,显示box盒子
ipt.addEventListener('focus', function() {
if (this.value !== '') {
box.style.display = 'block';
}
});
</script>
</body>
</html>