代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>speedTest</title>
<script src="../utils/code.jquery.com_jquery-3.7.0.js"></script>
<style>
.container {
width: 800px;
height: 500px;
background-color: aqua;
margin: auto;
position: relative;
}
.time {
width: 100%;
height: 100%;
line-height: 500px;
font-size: 50px;
color: #fff;
text-align: center;
font-weight: bold;
cursor: pointer;
position: absolute;
}
.test {
width: 180px;
height: 180px;
border-radius: 50%;
background-color: antiquewhite;
font-size: 30px;
font-weight: bold;
color: blueviolet;
line-height: 180px;
text-align: center;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="time"></div>
<div class="test">开始测试</div>
</div>
<script>
let startTime; //开始时间
let endTime; //点击时间
let flag = false; //提前点击的flag
let flagTime; //定时器flag
let count = 0;
let max = 4; //测试总次数
let avgTime = 0; //记录总时间
let flagStart = false; //开始flag
// 测试函数
function test() {
if (count >= max) { setTimeout(() => { alert(avgTime / max + "ms"); resetTest(); return; }, 1000) }
else {
count++;
let randTime = Math.floor(Math.random() * 3 + 3) * 1000;
setTimeout(() => {
$(".time").text("等待变色");
}, 1000)
flagTime = setTimeout(() => {
startTime = new Date().getTime();
$(".container").css("backgroundColor", color());
}, randTime)
}
}
// 颜色变换函数
function color() {
flag = true;
$(".time").text("");
return `rgb(${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)},${Math.floor(Math.random() * 256)})`
}
//重置函数
function resetTest() {
count = 0;
avgTime = 0;
flagStart = false;
clearTimeout(flagTime);
$(".test").css("display", "block");
$(".time").text("");
}
$(".container").mousedown(function () {
if (flagStart) {
if (!flag) {
alert("请不要提前点击!!!");
resetTest();
return;
}
endTime = new Date().getTime();
let time = endTime - startTime + "ms";
console.log(time);
$(".time").text(time);
avgTime += (endTime - startTime);
flag = false;
test();
}
})
$(".test").mousedown(function () {
event.stopPropagation();
$(".test").css("display", "none");
flagStart = true;
test();
})
</script>
</body>
</html>
上述代码通过设置测试函数以及颜色变化函数来使得测试的进行,通过鼠标按下事件mousedown来控制点击后的变化,以及下一次测试的推进,逻辑很简单,就时记录颜色开始变化的时间以及用户点击的时间,相减及得到了用户的反应速度。使用flag来避免用户的提前点击从而使得测试不准确,代码逻辑比较简单,不懂的话可以私信询问我。
效果图: