1.效果图
2.代码实现
index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><input type="text" id="input" ><span id="num1"></span><span id="op"></span><span id="num2"></span><span>=</span><span id="sum">?</span><button id="btn" onclick="sumbit()">提交</button><script src="./js/index.js"></script>
</body>
</html>
index.js
let num1_text = document.getElementById(`num1`)
let num2_text = document.getElementById(`num2`)
let sum_text = document.getElementById(`sum`)
let input = document.getElementById(`input`)
let op_text = document.getElementById(`op`)
let num1, num2, op
//生成随机数的方法
let rand = (min, max) => {//传入随机数范围result= parseInt((max-min+1)*Math.random()+min)//将结果转为整数return result //返回结果
}
//初始化方法
let init = () => {num1 = rand(1, 10)//生成一个1~10之间的随机数赋给num1num2 = rand(1, 10)//生成一个1~10之间的随机数赋给num2switch (rand(1, 4)) {//随机生成四则运算符case 1: op_text.textContent = `+`,op=`+`; break//当随机数为1为+,并将值赋给opcase 2: op_text.textContent = `-`, op = `-`; breakcase 3: op_text.textContent = `*`, op = `*`; breakcase 4: op_text.textContent = `/`, op = `/`; break}num1_text.textContent = `${num1}`//将当前num1的值显示到前端对应的标签中num2_text.textContent = `${num2}`
}
//页面加载时先执行一次
init()
//声明一个点击事件的方法
let sumbit = () => {//根据上面随机到的op,num1,num2结合获取到前端输入框中的值进行判断if (op == `+`&& parseInt(input.value)==(num1+num2)) alert("验证成功")else if (op == `-` && parseInt(input.value) == (num1 - num2)) alert("验证成功")else if (op == `*` && parseInt(input.value) == (num1 * num2)) alert("验证成功")else if (op == `/` && parseInt(input.value) == parseInt(num1 / num2)) alert("验证成功")else alert("验证失败")//提交后再次初始化init()
}