h5实现答题
使用HTML5实现答题功能
HTML5结合JavaScript可以轻松实现答题功能。以下是一个简单的答题系统实现方法:
HTML结构
<div id="quiz-container">
<h3 id="question"></h3>
<div id="options"></div>
<button id="submit">提交答案</button>
<div id="result"></div>
</div>
CSS样式
#quiz-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
#options {
margin: 20px 0;
}
.option {
display: block;
margin: 10px 0;
padding: 10px;
border: 1px solid #ddd;
cursor: pointer;
}
.option:hover {
background-color: #f5f5f5;
}
JavaScript逻辑
const quizData = [
{
question: "HTML5是什么时候发布的?",
options: ["2008", "2012", "2014", "2016"],
answer: "2014"
},
{
question: "哪个标签用于播放视频?",
options: ["<media>", "<video>", "<movie>", "<play>"],
answer: "<video>"
}
];
let currentQuestion = 0;
let score = 0;
function loadQuestion() {
const questionElement = document.getElementById('question');
const optionsElement = document.getElementById('options');
questionElement.textContent = quizData[currentQuestion].question;
optionsElement.innerHTML = '';
quizData[currentQuestion].options.forEach(option => {
const button = document.createElement('button');
button.textContent = option;
button.className = 'option';
button.onclick = function() {
selectOption(option);
};
optionsElement.appendChild(button);
});
}
function selectOption(option) {
const options = document.querySelectorAll('.option');
options.forEach(opt => {
opt.style.backgroundColor = '';
});
event.target.style.backgroundColor = '#d4edda';
document.getElementById('submit').onclick = function() {
checkAnswer(option);
};
}
function checkAnswer(selectedOption) {
if(selectedOption === quizData[currentQuestion].answer) {
score++;
document.getElementById('result').textContent = '正确!';
} else {
document.getElementById('result').textContent = '错误!';
}
currentQuestion++;
if(currentQuestion < quizData.length) {
loadQuestion();
} else {
document.getElementById('quiz-container').innerHTML = `
<h3>测验完成!</h3>
<p>你的得分: ${score}/${quizData.length}</p>
`;
}
}
loadQuestion();
实现答题功能的关键点
数据结构设计 使用数组存储问题和答案,每个问题对象包含问题文本、选项数组和正确答案。
{
question: "问题文本",
options: ["选项1", "选项2", "选项3", "选项4"],
answer: "正确答案"
}
界面交互 为每个选项创建按钮元素,并绑定点击事件。用户选择选项后高亮显示,提交按钮检查答案。
状态管理 使用currentQuestion变量跟踪当前问题索引,score变量记录得分。每回答一个问题后递增currentQuestion。
结果展示 所有问题回答完毕后显示总分,并提供重新开始的选项(可添加重新开始按钮)。
增强功能建议
本地存储 使用localStorage保存用户进度和最高分:
// 保存分数
localStorage.setItem('quizHighScore', score);
// 读取分数
const highScore = localStorage.getItem('quizHighScore') || 0;
计时功能 添加答题计时器:
let timeLeft = 30;
const timer = setInterval(() => {
timeLeft--;
document.getElementById('timer').textContent = timeLeft;
if(timeLeft <= 0) {
clearInterval(timer);
checkAnswer(null);
}
}, 1000);
随机问题顺序 打乱问题顺序增加可玩性:
quizData.sort(() => Math.random() - 0.5);
多种题型支持 扩展数据结构支持多选题、判断题等:

{
type: "multiple", // 单选/多选/判断
correctOptions: [0, 2] // 多选正确答案索引
}






