<html>
<head>
    <title>背景随机色</title>
    <script>
        function colorBackground() {
            var r = Math.floor(Math.random() * 0xff).toString(16);
            var g = Math.floor(Math.random() * 0xff).toString(16);
            var b = Math.floor(Math.random() * 0xff).toString(16);
            r = r.length == 2 ? r : "0" + r;
            g = g.length == 2 ? g : "0" + g;
            b = b.length == 2 ? b : "0" + b;
            var strclr = "#" + r + g + b;
            document.body.style.background = strclr;
        }
    </script>
</head>

<body>
    <form>
        <input type="button" value="随机改变背景色" onclick="colorBackground()">
    </form>
</body>
</html>

分析:

<!--在JS中,定义的所有对象都具有toString()方法。
Number类型的toString()方法比较特殊,有默认模式和基模式两种。

  • 默认模式的例子:

var num1 = 10;
var num2 = 10.0;
alert(num1.toString()); //输出10
alert(num2.toString()); //输出10
无论用什么表示法声明数字,默认模式只是按十进制返回。

  • 基模式的例子:

var num1 = 10;
alert(num1.toString(2)); //输出1010
alert(num1.toString(8)); //输出12
alert(num1.toString(16)); //输出A

很明显,基模式就是把数值型转换成相应的进制。-->

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2021-08-04
  • 2022-02-07
  • 2021-05-31
  • 2021-11-16
猜你喜欢
  • 2021-12-19
  • 2021-12-19
  • 2021-06-15
  • 2021-07-19
  • 2021-11-21
  • 2022-12-23
  • 2021-12-19
相关资源
相似解决方案