现在的位置: 首页 > 综合 > 正文

JavaScript随机数,demo小例子。

2012年09月10日 ⁄ 综合 ⁄ 共 750字 ⁄ 字号 评论关闭

随机数Math对象下的random方法,源码如下,可以直接使用。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title></title>
    <style type="text/css">
        .de{ width:450px; height:450px; border:4px solid #ccc; margin:0 auto; margin-top:50px;}
        .we{ width:450px; height:450px;}
    </style>
    <script type="text/javascript">
        function de() {
            var we = document.getElementById("we");
            var img = ["XMJ.jpg", "XMJX.jpg", "psb.jpg"];  //url 链接数组
            var allNumber = img.length;  // 保存img的个数
            var randomImg = parseInt(allNumber * Math.random());  //Math.random随机数
            we.setAttribute("src",img[randomImg]);
        }
        window.onload = function () {
            de();
        }
    </script>
</head>
<body>
    <div class="de">
        <img src="psb.jpg" alt="" title="" class="we" id="we" />
    </div>
</body>
</html>

抱歉!评论已关闭.