当我在输入值中键入内容时,我希望该输入值在键入时作为文本内容出现在span标记中

时间:2019-09-20 20:29:49

标签: javascript dom

键入时如何在span标记内看到输入值?

let input = document.querySelector("input");
input.addEventListener("keypress", function(e) {
  let span = document.querySelector("span");
  span.textContent = input.value
})
<span></span>
<input type="text">

2 个答案:

答案 0 :(得分:0)

使用事件keydown代替keypress,以便事件可以响应backspace的按下。还添加一个setTimeout以显示最后按下的键。

let input = document.querySelector("input");
input.addEventListener("keydown", function(e) {
  let span = document.querySelector("span");
  setTimeout(() => span.textContent = input.value);
})
<span></span>
<input type="text">

答案 1 :(得分:0)

使用事件击键来使其响应退格键。