zoukankan      html  css  js  c++  java
  • js随机更换

    如果想实现“随机”切换图像,那么我们要使用到几个Math()对象
    第一个是random()函数,函数的功能是产生随机数,如果书写为
    var a=Math.random()
    那么所产生的随机数是0-1(不包括1)
    如果我们想产生1-100的随机数怎么办呢?
    那么就使用random()*100即可得到0-100(不含100)的任意随机数(注意此时产生的数字并不只有整数)
    此时介绍另外3个Math()的函数
    ceil(),floor(),round()
    Math.round()        ------即四舍五入
    Math.ceil()              ------强制进位
    Math.floor()            ------强制舍去小数位
    因此,在此处如果系那个得到1-100的任意随机数,应该如此书写:
    var a=Math.ceil(Math.random()*100);
     
     1 <!DOCTYPE html>
     2 <html>  
     3 <head>      
     4 <title>js随机生成</title>      
     5 <meta http-equiv="Content-Type" content="textml; charset=utf-8">
     6 </head>    
     7 <body>  
     8 <button id="btn">点击</button>
     9 <div id="txt"></div>
    10 <script type="text/javascript">
    11         var bodyBgs = [];
    12             bodyBgs[0] = "1等奖";
    13             bodyBgs[1] = "2等奖";
    14             bodyBgs[2] = "3等奖";
    15             bodyBgs[3] = "4等奖";
    16             bodyBgs[4] = "5等奖";
    17             bodyBgs[5] = "6等奖";
    18             bodyBgs[6] = "7等奖";
    19             bodyBgs[7] = "8等奖";
    20             bodyBgs[8] = "9等奖";
    21             
    22         var btn = document.getElementById("btn");
    23         var txt = document.getElementById("txt");
    24         
    25             btn.onclick = function(){//点击输出随机的数字
    26                 var randomBgIndex = Math.round( Math.random() * 8 );
    27                 txt.innerHTML = bodyBgs[randomBgIndex];
    28             }             
    29 </script>
    30 </body> 
    31 </html>  
  • 相关阅读:
    财务对账系统设计
    工作中快速成长的10个技巧
    越来越火的"中台"是什么
    基于token的多平台身份认证架构设计
    了解Scala 宏
    Scala反射(一)
    一文学会Scala
    Scala 隐式转换及应用
    如何看MySql执行计划explain(或desc)
    sun.misc.Unsafe 详解
  • 原文地址:https://www.cnblogs.com/beiz/p/5069111.html
Copyright © 2011-2022 走看看