方法 | 含義 |
---|---|
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>
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號