本文旨在指导开发者如何使用HTML和JavaScript实现一个简单的问答游戏页面,该页面包含多个问题,每个问题有多个选项按钮。点击选项按钮后,当前问题区域隐藏,下一个问题区域显示。文章将详细讲解实现思路、关键代码以及注意事项,帮助读者快速掌握该功能的实现方法。
首先,我们需要构建页面的基本HTML结构。每个问题及其选项都包含在一个独立的 div 容器中。 使用 box 类作为所有 div 的基础样式,并使用 box1、box2 等类来区分不同的问题区域。
Awesome Quiz
Trivia Time ??!!!
Awesome Quiz
Who was the first President of the United States?
George Washington
Thomas Jefferson
Thomas Edinson
I don't Know
Question 1 of 5
Awesome Quiz
What is Queen Elizabeth II's surname?
Jason
Windsor
Drakeford
William
Question 2 of 5
Awesome Quiz
What is the largest country in the world?
Russia
Canada
India
South Africa
Question 3 of 5
接下来,使用JavaScript来实现点击按钮后切换 div 显示的效果。
获取元素:使用 document.querySelector 和 document.querySelectorAll 获取需要操作的HTML元素。 querySelector 返回匹配的第一个元素,而 querySelectorAll 返回所有匹配的元素列表。
绑定事件监听器:为每个选项按钮绑定点击事件监听器。
切换显示状态:在事件处理函数中,隐藏当前问题区域,显示下一个问题区域。
let start = document.querySelector('#start');
let intro = document.querySelector('.box1');
let box2 = document.querySelector('.box2');
let box3 = document.querySelector('.box3');
let box4 = document.querySelector('.box4');
let box5 = document.querySelector('.box5');
let box6 = document.querySelector('.box6');
start.addEventListener('click', function(){
intro.style.display = 'none';
box2.style.display = 'block';
})
// 获取box2下的所有option按钮
let select1 = document.querySelectorAll('.box2 .option');
// 循环绑定事件
select1.forEach(function(button) {
button.addEventListener('click', function(){
box2.style.display = 'none';
box3.style.display = 'block';
})
});
let select2 = document.querySelectorAll('.box3 .option');
select2.forEach(function(button) {
button.addEventListener('click', function(){
box3.style.display = 'none';
box4.style.display = 'block';
})
});
let select3 = document.querySelectorAll('.box4 .option');
select3.forEach(function(button) {
button.addEventListener('click', function(){
box4.style.display = 'none';
box5.style.display = 'block';
})
});将HTML和JavaScript代码整合在一起,得到完整的代码示例:
Awesome Quiz Awesome Quiz
Trivia Time ??!!!
Awesome Quiz
Who was the first President of the United States?
George Washington
Thomas Jefferson
Thomas Edinson
I don't Know
Question 1 of 5
Awesome Quiz
What is Queen Elizabeth II's surname?
Jason
Windsor
Drakeford
William
Question 2 of 5
Awesome Quiz
What is the largest country in the world?
Russia
Canada
India
South Africa
Question 3 of 5
返回所有匹配的元素列表。 在需要操作多个元素时,务必使用 querySelectorAll,并循环处理每个元素。通过本文的讲解,您应该能够使用HTML和JavaScript实现一个简单的问答游戏页面,并理解其中的核心概念和实现方法。 希望本文对您有所帮助!