<JavaScript> 四. Math对象的属性和方法

  1 <!DOCTYPE html>
  2 <html>
  3 <head>
  4 <!-- 定时刷新网页 -->
  5 <!-- <meta http-equiv="refresh" content="1"> -->
  6     <title></title>
  7 <script type="text/javascript">
  8 /*
  9     Math对象
 10     静态对象, 不需要创建实例, 可以直接使用
 11 */
 12 
 13 // 圆周率
 14 document.write(Math.PI);
 15 document.write("<hr>");
 16 
 17 // 绝对值
 18 document.write(Math.abs(-9));
 19 document.write("<hr>");
 20 
 21 // 向上取整 去掉小数, 整数+1
 22 document.write(Math.ceil(3.2));
 23 document.write("<hr>");
 24 
 25 // 向下取整 去掉小数
 26 document.write(Math.floor(3.9));
 27 document.write("<hr>");
 28 
 29 // 四舍五入
 30 document.write(Math.round(3.5));
 31 document.write("<hr>");
 32 
 33 document.write(Math.round(3.1));
 34 document.write("<hr>");
 35 
 36 // x的y次方
 37 document.write(Math.pow(2, 24));
 38 document.write("<hr>");
 39 
 40 // 开方
 41 document.write(Math.sqrt(16));
 42 document.write("<hr>");
 43 
 44 // 0 - 1 的随机数
 45 document.write(Math.random());
 46 document.write("<hr>");
 47 
 48 // 实例1: 两个数之间的随机整数
 49 function getRandom(min, max) {
 50 
 51     // 随机整数
 52     random = Math.random() * (max - min) + min;
 53 
 54     // 向下取整
 55     random = Math.floor(random);
 56 
 57     // 返回随机整数
 58     return random;
 59 }
 60 
 61 // 调用函数
 62 document.write(getRandom(0, 10));
 63 document.write("<hr>");
 64 
 65 // 实例2: 随机网页背景色
 66 
 67 // 得到随机颜色值
 68 // (1) 三个随机数并转换为16进制
 69 var red = getRandom(0, 256).toString(16);
 70 var green = getRandom(0, 256).toString(16);
 71 var blue = getRandom(0, 256).toString(16);
 72 var color = "#" + red + green + blue;
 73 // document.write(red + " ");
 74 // document.write(green  + " ");
 75 // document.write(blue + " ");
 76 
 77 // (2) 写CSS样式
 78 var str = "";
 79 str += '<style type="text/css">';
 80 str += 'body {';
 81 str += '    background-color:' + color + ';';
 82 str += '}';
 83 str += '</style>';
 84 
 85 // 将CSS样式写入网页
 86 // document.write(str);
 87 
 88 // 第二种方式
 89 // (1) 得到随机颜色值
 90 var color = "#" + (getRandom(0, Math.pow(2, 24)).toString(16));
 91 
 92 /* (2) 设置网页背景色
 93     document: 网页对象
 94     body: 子对象
 95     bgColor: body的属性
 96     除了body以外, 其它标记必须使用id来访问
 97 */
 98 document.body.bgColor = color;
 99 </script>
100 </head>
101 <body>
102 
103 </body>
104 </html>
原文地址:https://www.cnblogs.com/ZeroHour/p/6364628.html