js部分function createOneSnow(){ var leftX = Math.random()*window.innerWidth; var topY = Math.random()*window.innerHeight; var snowDiv = document.createElement("div"); snowDiv.style.position = "fixed"; snowDiv.style.left = leftX + "px"; snowDiv.style.top = topY + "px"; var targetImg= document.createElement("img"); targetImg.src = 'image/white-snow.png'; targetImg.style.width = '20px'; snowDiv.appendChild(targetImg); document.body.appendChild(snowDiv);}function createManySnow(){ for (var i = 0 ; i < 20 ; i++) { createOneSnow(); }}function startFly(){ var allSnows = document.getElementsByTagName("div"); snowLength = allSnows.length; for (var i = 0 ; i < snowLength; i++) { var randomTop = Math.random()*6; allSnows[i].style.top = allSnows[i].offsetTop + randomTop + "px"; if( allSnows[i].offsetTop % 500 == 0 ) { createOneSnow(); } if(allSnows[i].offsetTop > window.innerHeight){ allSnows[i].remove(); createOneSnow(); } } document.getElementById("startButton").disabled = "disabled"; document.getElementById("stopButton").disabled = "";} function stopFly(){ clearInterval(timer); document.getElementById("startButton").disabled = ""; document.getElementById("stopButton").disabled = "disabled";} window.onload=function(){ createManySnow(); setInterval(startFly,100);}html部分<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>fly</title> <link rel="stylesheet" href="p1.css"> <script src="p1.js"></script></head>网页打开后,雪花自动产生并落下,但是按下 stop键,stopFly函数失灵,估计是无法找到 timer,clearInterval(timer); 无法执行。请问,如何让onclick="stopFly();" 起作用?全部代码,image,本问题涉及的源代码请下载。
2 回答
慕丝7291255
TA贡献1859条经验 获得超6个赞
var timer = null;
window.onload=function(){
createManySnow();
timer = setInterval(startFly,100);
}
大佬,你一开始timer都没有定义,怎么清掉。按上面加就可以了。
Smart猫小萌
TA贡献1911条经验 获得超7个赞
var timer;
window.onload=function(){
createManySnow();
_startFly();
}
function _startFly(){
timer=setInterval(startFly,100);
}
-
<input type="button" id="startButton" value="开始" onclick="_startFly()">
添加回答
举报
0/150
提交
取消