如何在HTML中实时显示<input>输入框的内容?
实现输入内容实时显示在输入框上方
你可以通过添加显示容器 + 监听输入事件来实现这个功能,以下是修改后的完整代码:
<center> <!-- 用来实时显示输入内容的容器 --> <h1 id="nameDisplay"></h1> <input tag='name' type='text' placeholder="Name" maxlength="10" minlength="2" id="nameInput"> <br> <input tag='pass' type='password' minlength='7' maxlength='20' placeholder="Password" > <input type='submit'> </center> <script> // 获取输入框和显示元素 const nameInput = document.getElementById('nameInput'); const nameDisplay = document.getElementById('nameDisplay'); // 监听input事件,用户输入/删除/粘贴时实时同步内容 nameInput.addEventListener('input', function() { nameDisplay.textContent = this.value; }); </script>
关键说明:
- 给显示区域(复用了原有的
<h1>)添加唯一id,方便JavaScript定位元素 - 使用
input事件监听输入框内容变化,这个事件能覆盖所有用户修改内容的操作(输入、删除、右键粘贴等),确保同步的实时性 - 如果需要给密码框也添加类似效果,只需要重复逻辑:新增显示容器、给密码框加
id、添加对应的监听事件即可
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

