JavaScript汽车赛跑程序获胜弹窗提示及图片重置功能实现问题
代码修复方案
核心问题说明
StartRace获胜判定逻辑错误:原判定仅在点击启动按钮时执行一次,未跟随定时器每次位移后触发;同时判定逻辑直接对比DOM对象和800px字符串,且仅判断等于的情况,不符合随机位移的实际运行场景;获胜后也没有清除定时器停止车辆移动。ResetRace复位逻辑错误:原代码使用相等判断符==执行赋值操作,未实际修改车辆的位置属性,也没有清除运行中的定时器,会出现复位后车辆继续移动的问题。
修复后完整代码
JavaScript
var timer; var ArandomNumber; var BrandonNumber; var x = 0 var q = 0 function GatherData() { ArandomNumber = GetRandomNumA(); BrandonNumber = GetRandomNumB(); var thedivtop = document.getElementById("Move1"); x += ArandomNumber; thedivtop.style.marginLeft = x + 'px'; var thedivbottom = document.getElementById("Move2"); q += BrandonNumber; thedivbottom.style.marginLeft = q + 'px'; // 位移更新后立即判定胜负 if (x >= 800 && q < 800) { clearInterval(timer); alert("Car 1 has won the race!"); } else if (q >= 800 && x < 800) { clearInterval(timer); alert("Car 2 has won the race!"); } else if (x >= 800 && q >= 800) { clearInterval(timer); alert("双方平局!"); } } function StartRace() { // 避免多次点击启动多个定时器 if(timer) clearInterval(timer); timer = setInterval(GatherData, 500); } function GetRandomNumA() { var x = Math.random(); x = Math.random() + 56; return x; } function GetRandomNumB() { var q = Math.random(); q = Math.random() + 56; return q; } function PauseRace() { clearInterval(timer); } function ResetRace() { clearInterval(timer); timer = null; x = 0; q = 0; // 修正赋值逻辑,正确复位车辆位置 document.getElementById("Move1").style.marginLeft = '0px'; document.getElementById("Move2").style.marginLeft = '0px'; }
CSS
.moveable { position: absolute; height: 100px; width: 200px; }
HTML
(已修复重复ID问题,可选修改)
<body> <b>First to 800 pixels wins!</b> <br> <br> <b>Both cars start at 0 pixels.</b> <br> <br> <input id="StartBtn" type="button" value="Start Race" onclick="StartRace()" /> <input id="PauseBtn" type="button" value="Pause Race" onclick="PauseRace()" /> <input id="ResetBtn" type="button" value="Reset Cars" onclick="ResetRace()" /> <br> <br> <div id="Move1"> <img id="Car1" class="moveable" src="delorean.jpeg" alt="赛车1" /> </div> <br><br><br><br><br><br> <div id="Move2"> <img id="Car2" class="moveable" src="duster.jpg" alt="赛车2" /> </div> </body>
内容的提问来源于stack exchange,提问作者user14391204
相关产品推荐
相关产品推荐

