JavaScript随机数


JavaScript #随机数2012-05-18 23:53

利用随机数Math对象下的random方法。看下面的例子。

01<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
03<head>
04    <title></title>
05    <style type="text/css">
06        .de{ width:450px; height:450px; border:4px solid #ccc; margin:0 auto; margin-top:50px;}
07        .we{ width:450px; height:450px;}
08    </style>
09    <script type="text/javascript">
10        function de() {
11            var we = document.getElementById("we");
12            var img = ["XMJ.jpg", "XMJX.jpg", "psb.jpg"];  //url 链接数组
13            var allNumber = img.length;  // 保存img的个数
14            var randomImg = parseInt(allNumber * Math.random());  //Math.random随机数
15            we.setAttribute("src",img[randomImg]);
16        }
17        window.onload = function () {
18            de();
19        }
20    </script>
21</head>
22<body>
23    <div class="de">
24        <img src="psb.jpg" alt="" title="" class="we" id="we" />
25    </div>
26</body>
27</html>


相关文章

粤ICP备11097351号-1