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,本问题涉及的源代码请下载。
慕丝7291255
Smart猫小萌
相关分类