js图片随机切换
使用js做到随机切换图片
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <img src="1.jpg" width="280px" height="280px" id="tpid" style="display: block; margin: auto;"><br><br> <button onclick="aa()"style="display: block; margin: auto;">开始</button> <button onclick="bb()"style="display: block; margin:20px auto;">四秒后停止</button> <script> var sj; var tpm; var intervalId; function bb(){setTimeout(function() {clearInterval(intervalId);},4000)} function aa(){intervalId=setInterval(function() {sj=parseInt(Math.random()*3+1); tpm=sj+".jpg"; document.getElementById("tpid").src=tpm;},50)} </script> </body> </html>
效果如下: