<!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>


本文详细介绍了如何使用HTML和JavaScript实现输入框的实时显示功能,通过键盘按键事件的监听,实现了输入框内容变化时,实时更新显示在页面上的内容预览。同时,还包含了如何在输入框失去焦点和获得焦点时,控制预览内容的显示与隐藏。
1020

被折叠的 条评论
为什么被折叠?



