1
/
5

クイズアプリ

こんにちは!株式会社アルシエで教育に関するサポートをしている岸本です。

今回は「JavaScriptでクイズアプリを作成する」についてお伝えしていきます。

プロジェクトのセットアップ

まず、プロジェクトのディレクトリを作成し、基本的なファイルを用意します。

mkdir quiz-app
cd quiz-app
touch index.html app.js styles.css

HTMLの構造

index.html ファイルにクイズアプリの基本的なHTML構造を追加します。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>クイズアプリ</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="quiz-container">
<h1>クイズアプリ</h1>
<p id="question">ここに質問が表示されます。</p>
<ul id="choices" class="choices-list">
<!-- 選択肢がここに表示されます -->
</ul>
<button id="next-button">次へ</button>
<p id="score">スコア: 0</p>
</div>
<script src="app.js"></script>
</body>
</html>

クイズデータの作成

app.jsに記入します。

const quizData = [
{
question: "JavaScriptの設計者は誰でしょうか?",
choices: ["Brendan Eich", "Mark Zuckerberg", "Jeff Bezos", "Elon Musk"],
correct: 0, // 正解の選択肢のインデックス
},
// 他のクイズデータもここに追加
];

HTMLの構築

クイズ画面のレイアウト

HTMLファイル (index.html) にクイズ画面の基本的なレイアウトを追加します。

<div class="quiz-container">
<h1>クイズアプリ</h1>
<p id="question">ここに質問が表示されます。</p>
<ul id="choices" class="choices-list">
<!-- 選択肢がここに表示されます -->
</ul>
<button id="next-button">次へ</button>
<p id="score">スコア: 0</p>
</div>

このHTMLコードでは、質問、選択肢、次へボタン、スコアを表示する要素があります。

CSSのスタイリング

クイズ画面のデザイン

CSSファイル (styles.css) を使用して、クイズ画面のデザインをカスタマイズします。スタイルを追加してアプリを魅力的に見せましょう。

/* クイズ画面のスタイル */
.quiz-container {
text-align: center;
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #f0f0f0;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

CSSコードはクイズ画面のコンテナ要素に適用され、テキストの配置、背景色、ボックスシャドウなどを設定します。

JavaScriptの実装

クイズの質問と選択肢を表示する関数

JavaScriptファイル (app.js) にクイズの質問と選択肢を表示する関数を実装します。

function displayQuestion() {
const currentQuestion = quizData[currentQuestionIndex];
questionElement.textContent = currentQuestion.question;

// 選択肢をクリア
choicesElement.innerHTML = "";

// 選択肢を表示
currentQuestion.choices.forEach((choice, index) => {
const choiceElement = document.createElement("li");
choiceElement.textContent = choice;
choiceElement.addEventListener("click", () => checkAnswer(index));
choicesElement.appendChild(choiceElement);
});
}
displayQuestion()

この関数は、クイズデータから現在の質問を取得し、質問と選択肢をHTML要素に表示します。

ユーザーの回答をチェックする関数

次に、ユーザーの回答をチェックし、正解かどうかを判定する関数を実装します。

function checkAnswer(selectedIndex) {
const currentQuestion = quizData[currentQuestionIndex];
if (selectedIndex === currentQuestion.correct) {
// 正解の場合
score++;
}
currentQuestionIndex++;

if (currentQuestionIndex < quizData.length) {
// 次の質問がある場合、次の質問を表示
displayQuestion();
} else {
// クイズ終了
showResult();
}
}

この関数では、選択された選択肢のインデックスを受け取り、正解かどうかを判定し、スコアを更新します。

また、次の質問を表示するか、クイズが終了した場合は結果を表示します。

スコアの計算と表示

スコアを計算し、HTMLに表示する関数を実装します。

function showResult() {
scoreElement.textContent = `スコア: ${score} / ${quizData.length}`;
}

以上です。


株式会社アルシエ's job postings
1 Likes
1 Likes

Weekly ranking

Show other rankings
Invitation from 株式会社アルシエ
If this story triggered your interest, have a chat with the team?