You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:57:08