代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> button { font-size: 20px; padding: 5px 30px; margin-left: 20px; } span { width: 100px; height: 100px; border-radius: 50px; background-color: red; display: inline-block; margin-top: 30px; margin-left: 20px; color: white; font-size: 40px; text-align: center; line-height: 100px; } </style> </head> <body> <!-- --> <button>开始</button> <button>停止</button> <br> <span id="aaa"></span> <span></span> <span></span> <span></span> <span></span> <span></span> <span style="background-color: #06c;"></span> <script> //1.获取元素 var btns = document.getElementsByTagName("button"); var spans = document.getElementsByTagName("span"); //4.声明一个变量 用来记录 当前要停止的小球的索引 var n = 0; var timer = null; //2.点击 开始 让所有小球中的内容 进行自动切换 btns[0].onclick = function () { //0-30 timer = setInterval(function () { //切换一次的代码 for (var i = n; i < spans.length; i++) { var ran = parseInt(Math.random() * 31); spans[i].innerText = ran; } }, 50) } //3.点击 停止按钮 让正在切换的第一个小球停下来 btns[1].onclick = function () { setTimeout(function () { n++;//1 2 //1.当全部停止之后 要清除定时器 if(n>=7){ clearInterval(timer); n = 0;//2.在停止之后 可以重新开始的 } }, 500) } </script> </body> </html>