本文将介绍图片随机显示相关的js脚本
你需要准备好需要随机显示的图片,后缀名最好一样的
1.将所有的文件名称写到数组中,或者循环,随便你好啦~
var imgArr = ['p01','p02','p03'];
2.生成随机数,并用这个随机数在数组中取值
var rand = Math.random() * 100; rand = Math.floor(rand) % imgArr.length; var img = imgArr[rand] + ".png";
3.最后进行赋值~
var img = document.getElementsByTagName("img")[0]; img.src = img;
最后给出代码的集合,我在这里把这个数组和赋值函数封装到了一起
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>我爱你❤️据说每个人扫出来的不一样哟~</title> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <style type="text/css"> body{background-color: #fff;} div{ width: 100%; float: left; position: relative; min-height: 1px; box-sizing: border-box; display: block; } img{ display: block; margin-right: auto; margin-left: auto; max-width: 100%; height: auto; padding-top:132px; } </style> </head> <script language="JavaScript"> window.onload = function() { o.imgRandom(); } var o = { aImg: [ 'p01', 'p02', 'p03' ], imgRandom: function() { var img = document.getElementsByTagName("img")[0]; var b = Math.random() * 100; b = Math.floor(b) % (this.aImg.length); img.src = this.aImg[b] + ".png"; } }; </script> <body onselectstart="return false"> <div> <img name="randimg" src="img/a1.png"> </div> </body> </html>
微信扫码查看本文
发表评论