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

实时修改div宽度的JavaScript函数异常问题求助

解决实时修改div宽度的输入事件问题

我看你遇到的问题核心是事件触发时机不对导致的,咱们一步步来搞定它:

问题根源

你用的onkeypress事件会在字符被输入到输入框之前就触发,这就导致:

  • 第一次输入字符时,输入框的value还没更新,函数自然拿不到这个值
  • 修改数值时,新输入的字符还没写入输入框,函数读取的还是旧值,得等下一次按键才会生效

纯JavaScript解决方案

把触发事件换成input事件就完美解决了——这个事件会在输入框内容实际发生变化时触发,不管是键盘输入、粘贴、删除甚至用鼠标操作,都能实时响应。

修改后的完整代码如下:

<!DOCTYPE html>
<html>
<head>
<title>gr</title>
<style>#in{ border:1px solid grey; height: 200px; width: 100%; transition: all 1s; }</style>
</head>
<body>
<div id='in'></div>
<!-- 把onkeypress换成oninput -->
<input type="text" id='sisse' oninput="change()">
<script>
function change(){
  const inputVal = document.getElementById('sisse').value;
  // 加个简单校验,避免空值导致宽度异常
  const width = inputVal ? inputVal + 'px' : '100%';
  document.getElementById('in').style.width = width;
}
</script>
</body>
</html>

额外优化(可选)

如果想更贴合现代JS写法,推荐用addEventListener绑定事件,实现HTML和JS逻辑分离,维护起来更方便:

<!DOCTYPE html>
<html>
<head>
<title>gr</title>
<style>#in{ border:1px solid grey; height: 200px; width: 100%; transition: all 1s; }</style>
</head>
<body>
<div id='in'></div>
<input type="text" id='sisse'>
<script>
const input = document.getElementById('sisse');
const targetDiv = document.getElementById('in');

input.addEventListener('input', function() {
  const inputVal = this.value;
  targetDiv.style.width = inputVal ? `${inputVal}px` : '100%';
});
</script>
</body>
</html>

这样不管你是第一次输入数值,还是修改现有数值,div的宽度都会实时跟着变化,用户体验就好很多啦~

内容的提问来源于stack exchange,提问作者Indrek Hints

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:11:53