JavaScript:数学对象,随机生成数字验证码并且随机添加字体颜色
一.方法
方法 |
含义 |
Math.floor() |
向下取整 |
Math.celi() |
向上取整 |
Math.random() |
随机生成0-1的数值 |
二.随机生成数字验证码并且随机添加字体颜色
三.代码块,可看注释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>生成随机数</title>
</head>
<body>
<div class="box">
<span
style="background-color: lightblue; font-weight: 600; padding: 5px"
></span>
</div>
<script>
//生成0-1的随机数 random
// console.log(Math.floor(Math.random() * 4));
//随机生成验证码
//首先建立一个字符串
let str =
"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNNM1234567890";
//把字符串转为数组,并且分隔开字符
let arr = str.split("");
// 建立一个储存数值的变量
let result = "";
for (let i = 0; i < 4; i++) {
let n = Math.floor(Math.random() * arr.length);
result += arr[n];
}
// 随机生成颜色
function show() {
let r = Math.floor(Math.random() * (255 + 1));
let g = Math.floor(Math.random() * (255 + 1));
let b = Math.floor(Math.random() * (255 + 1));
let rgb = "rgb" + "(" + r + "," + g + "," + b + ")";
return rgb;
}
// console.log(show());
//把随机生成的字符添加到span里面
let yzm = document.querySelector(".box > span").append(result);
////给span添加随机颜色
let Span = (document.querySelector(".box >span").style.color = show());
</script>
</body>
</html>