JavaScript猜数字游戏点击Again重置按钮后页面变形问题咨询
问题原因
导致点击重置按钮后布局变形的核心错误出在again按钮的点击事件处理逻辑中:
- 你本来需要重置猜对数字时被修改为
30rem的.number元素宽度,结果错误选中了body元素,给整个页面的容器设置了15rem的固定宽度,直接把页面挤窄导致布局错乱。 - 同时你还存在一个逻辑问题:
again回调里用var number声明了局部变量,没有修改全局的目标数字变量,重置后游戏会沿用旧的目标数字,逻辑异常。
修复方案
把again按钮的事件处理代码替换为以下内容即可:
document.querySelector(".again").addEventListener("click", function(){ score = 20; // 直接修改全局目标数字,不要重复声明局部变量 number = Math.trunc(Math.random() * 20) + 1; document.querySelector(".message").textContent = "Start guessing..."; document.querySelector(".score").textContent = score; document.querySelector(".number").textContent = "?"; document.querySelector(".guess").value = ""; document.querySelector("body").style.backgroundColor = "#222"; // 修正:重置.number的宽度为初始值,不要修改body的宽度 document.querySelector(".number").style.width = "15rem"; });
内容的提问来源于stack exchange,提问作者Albert Rmz
相关产品推荐
相关产品推荐

