一共5张图,随机数算法[1,5]:
生成n-m,包含n和m的随机数:
第一步算出 m-n的值,假设等于w
第二步Math.random()*w
第三步Math.random()*w+n
第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>定时随机切换图片 </title>
<style type="text/css">
</style>
</head>
<body>
<img src="images/banana1.jpg">
</body>
<script type="text/javascript">
var imgs = document.getElementsByTagName('img')
setInterval(
function() {
var rand = Math.ceil(Math.random() * 10);
imgs[0].src = "images/banana"+Math.round(Math.random()*4+1)+".jpg";
}, 2000);
</script>
</html>
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>定时随机切换图片 </title> <style type="text/css"> #box { width: 720px; height: 480px; margin: 15px auto; border: 1px solid red; overflow: hidden; } .pic1 { display: block; float: left; width: 352px; height: 220px; margin: 4px; } .pic2 { display: block; float: left; width: 236px; height: 130px; margin: 1.5px; } .pic3 { display: block; float: left; width: 175px; height: 111px; margin: 2px; } </style> </head> <body> <div id="box"> <img class="pic1" src="img/1.jpg"> <img class="pic1" src="img/2.jpg"> <img class="pic2" src="img/3.jpg"> <img class="pic2" src="img/4.jpg"> <img class="pic2" src="img/5.jpg"> <img class="pic3" src="img/6.jpg"> <img class="pic3" src="img/7.jpg"> <img class="pic3" src="img/8.jpg"> <img class="pic3" src="img/9.jpg"> </div> </body> <script type="text/javascript"> setInterval( function() { var imgs = document.getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { imgs[i].src = "img/" + Math.round(Math.random() * 8 + 1) + ".jpg"; } }, 2000); </script> </html>
时间: 2024-11-08 18:44:01