<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>口算小练习</title>
<style>
#que { font-size: 24px; }
</style>
</head>
<body>
<p id="que">题目</p>
<input id="my" autofocus placeholder="输入答案,回车提交"><br><br>
<button id="ente">确定</button>
<button id="canser">取消</button>
<script>
function randint(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
const que = document.getElementById('que');
const my = document.getElementById('my');
const ente = document.getElementById('ente');
let a, b;
// ★ 一打开就自动执行
function newQuestion() {
a = randint(1, 100);
b = randint(1, 100);
que.innerText = `题目:${a}+${b} = ?`;
my.value = '';
my.focus();
}
window.onload = newQuestion; // 打开就出题
// 判答案
ente.addEventListener('click', () => {
if (Number(my.value) === a + b) {
que.innerText = '✅ 答对啦!下一题:';
newQuestion();
} else {
que.innerText = `❌ 不对哦,${a}+${b} 等于几?`;
my.value = '';
my.focus();
}
});
// 回车也能提交
my.addEventListener('keydown', e => {
if (e.key === 'Enter') ente.click();
});
// 取消:直接换一题
document.getElementById('canser').addEventListener('click', newQuestion);
</script>
</body>
</html>