JQuery CSS3 实现限时答题的游戏,请给出示例代码。
时间: 2024-05-13 09:14:57 浏览: 77
以下是一个简单的 JQuery CSS3 实现限时答题游戏的示例代码:
HTML 代码:
```html
<div id="quiz">
<h2>限时答题游戏</h2>
<div id="question"></div>
<div id="choices"></div>
<div id="timer">倒计时: <span id="countdown">30</span>秒</div>
<button id="start">开始</button>
</div>
```
CSS3 代码:
```css
@keyframes blink {
50% {
color: black;
background-color: yellow;
}
}
#timer {
font-size: 20px;
font-weight: bold;
margin-top: 20px;
}
#countdown {
animation: blink 1s linear infinite;
}
.choice {
display: inline-block;
margin-right: 10px;
margin-bottom: 10px;
padding: 10px;
border: 2px solid #ccc;
border-radius: 5px;
cursor: pointer;
}
.choice:hover {
background-color: #ccc;
}
```
JQuery 代码:
```js
$(document).ready(function() {
// 定义问题和答案
var questions = [
{
question: "哪个月是一年中天数最少的月份?",
choices: ["2月", "4月", "6月", "9月"],
correctAnswer: 0
},
{
question: "夏天,人们喜欢吃哪种水果?",
choices: ["苹果", "香蕉", "西瓜", "橙子"],
correctAnswer: 2
},
{
question: "动物园里有几只大象?",
choices: ["1只", "2只", "3只", "4只"],
correctAnswer: 1
}
];
var currentQuestion = 0;
var correctAnswers = 0;
var quizOver = false;
// 显示问题
function displayCurrentQuestion() {
var question = questions[currentQuestion].question;
var choices = questions[currentQuestion].choices;
// 显示问题
$("#question").text(question);
// 显示选项
for (var i = 0; i < choices.length; i++) {
var choice = choices[i];
var html = "<div class='choice' data-index='" + i + "'>" + choice + "</div>";
$("#choices").append(html);
}
}
// 开始游戏
$("#start").click(function() {
$(this).hide();
displayCurrentQuestion();
startTimer();
});
// 点击选项
$("#choices").on("click", ".choice", function() {
if (quizOver) {
return;
}
var index = $(this).data("index");
var correctAnswer = questions[currentQuestion].correctAnswer;
// 判断答案是否正确
if (index === correctAnswer) {
$(this).css("background-color", "green");
correctAnswers++;
} else {
$(this).css("background-color", "red");
}
// 下一题
currentQuestion++;
setTimeout(function() {
if (currentQuestion < questions.length) {
displayCurrentQuestion();
} else {
displayScore();
stopTimer();
quizOver = true;
}
}, 1000);
});
// 显示分数
function displayScore() {
var html = "<h3>你的得分是: " + correctAnswers + " / " + questions.length + "</h3>";
$("#quiz").append(html);
}
// 倒计时
var countdown = 30;
var timer = null;
function startTimer() {
timer = setInterval(function() {
countdown--;
$("#countdown").text(countdown);
if (countdown === 0) {
stopTimer();
displayScore();
quizOver = true;
}
}, 1000);
}
function stopTimer() {
clearInterval(timer);
}
});
```
在这个示例代码中,我们使用了 CSS3 动画来创建一个闪烁的效果来提醒用户剩余时间。我们还使用了 JQuery 来处理用户的输入,并实现了一个简单的倒计时功能。
阅读全文