1. 通过 JS 添加样式
<script>
var box = document.getElementById("box");
box.style.width = "200px";
box.style.height = "200px";
box.style["backgroundColor"] = "red";
</script>
2. 随机数
2.1 随机生成一个 0-1 之间的小数:Math.radom()
<script>
var num = Math.random();
console.log(num);
var a = Math.random() * 100;
console.log(a);
</script>
2.2 向下取整:Math.floor()
<script>
var b = Math.floor(Math.random() * 100) + 1;
console.log(b);
</script>
2.3 案例:打开网页 随机改变网页的背景颜色
<script>
var colors = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
var color = "#";
for (var i = 0; i < 6; i++) {
var index = Math.floor(Math.random() * colors.length);
color += colors[index];
}
document.body.style.background = color;
</script>