js实现点击上一题和下一题出现对应的题目,

本文介绍了一个基于HTML、CSS和JavaScript构建的在线测验系统,该系统采用动态加载页面技术,实现了测验题目和答案的选择、提交及结果展示功能。测验包含多个选择题,涉及中国菜系、茶叶分类等知识领域,用户可以通过前后翻页和提交按钮进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
        <title>测验表2</title>
        <style type="text/css">
            @import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);
            body {
                font-size: 20px;
                font-family: 'Work Sans', sans-serif;
                color: #333;
                font-weight: 300;
                text-align: center;
                background-color: #f8f6f0;
            }
            
            h1 {
                font-weight: 300;
                margin: 0px;
                padding: 10px;
                font-size: 16px;
                background-color: #444;
                color: #fff;
            }
            
            .question {
                font-size: 30px;
                margin-bottom: 10px;
            }
            
            .answers {
                margin-bottom: 20px;
                text-align: left;
                display: inline-block;
            }
            
            .answers label {
                display: block;
                margin-bottom: 10px;
            }
            
            button {
                font-family: 'Work Sans', sans-serif;
                font-size: 16px;
                background-color: #279;
                color: #fff;
                border: 0px;
                border-radius: 3px;
                padding: 10px;
                cursor: pointer;
                margin-bottom: 20px;
                margin-top: 20px;
            }
            
            button:hover {
                background-color: #38a;
            }
            
            .slide {
                position: absolute;
                left: 0px;
                top: 0px;
                width: 100%;
                z-index: 1;
                opacity: 0;
                transition: opacity 0.5s;
            }
            
            .active-slide {
                opacity: 1;
                z-index: 2;
            }
            
            .quiz-container {
                position: relative;
                height: 200px;
                margin-top: 40px;
            }
        </style>
    </head>

    <body>
        <h1>测试表</h1>
        <div class="quiz-container" style="margin-bottom: 100px;">
            <div id="quiz"></div>
        </div>
        <button id="previous">前一题</button>
        <button id="next">下一题</button>
        <button id="submit">提交</button>
        <div id="results"></div>
        <script type="text/javascript">
            (function() {
                const myQuestions = [{
                        question: "“大煮干丝”是哪个菜系的代表菜之一( )。",
                        answers: {
                            A: "四川菜系",
                            B: "山东菜系",
                            C: "广东菜系",
                            D: "淮扬菜系"
                        },
                        correctAnswer: "D"
                    },
                    {
                        question: "红茶属于( )茶。",
                        answers: {
                            A: "半发酵",
                            B: "发酵",
                            C: "不发酵",
                            D: "微发酵"
                        },
                        correctAnswer: "A"
                    },
                    {
                        question: "满汉全席起兴于( )。",
                        answers: {
                            A: "清代",
                            B: "唐代",
                            C: "宋代",
                            D: "两汉"
                        },
                        correctAnswer: "A"
                    },
                    {
                        question: "满汉全席起兴于( )。",
                        answers: {
                            A: "清代",
                            B: "清代",
                            C: "清代",
                            D: "两汉"
                        },
                        correctAnswer: "ABC"
                    }
                ];

                function buildQuiz() {
                    // we'll need a place to store the HTML output
                    const output = [];

                    // for each question...
                    myQuestions.forEach((currentQuestion, questionNumber) => {
                        // we'll want to store the list of answer choices
                        const answers = [];

                        // and for each available answer...
                        for(letter in currentQuestion.answers) {
                            // ...add an HTML radio button
                            if(currentQuestion.correctAnswer.length > 1) {
                                answers.push(
                                    `<label>
                         <input type="checkbox" name="question${questionNumber}" value="${letter}">
                          ${letter} :
                          ${currentQuestion.answers[letter]}
                       </label>`
                                );
                            } else {
                                answers.push(
                                    `<label>
                         <input type="radio" name="question${questionNumber}" value="${letter}">
                          ${letter} :
                          ${currentQuestion.answers[letter]}
                       </label>`
                                );
                            }

                        }

                        // add this question and its answers to the output
                        output.push(
                            `<div class="slide">
                   <div class="question"> ${currentQuestion.question} </div>
                   <div class="answers"> ${answers.join("")} </div>
                 </div>`
                        );
                    });

                    // finally combine our output list into one string of HTML and put it on the page
                    quizContainer.innerHTML = output.join("");
                }

                function showResults() {
                    // gather answer containers from our quiz
                    const answerContainers = quizContainer.querySelectorAll(".answers");

                    // keep track of user's answers
                    let numCorrect = 0;

                    // for each question...
                    myQuestions.forEach((currentQuestion, questionNumber) => {
                        // find selected answer
                        const answerContainer = answerContainers[questionNumber];
                        const selector = `input[name=question${questionNumber}]:checked`;
                        const userAnswer = (answerContainer.querySelector(selector) || {}).value;

                        // if answer is correct
                        if(userAnswer === currentQuestion.correctAnswer) {
                            // add to the number of correct answers
                            numCorrect++;

                            // color the answers green
                            answerContainers[questionNumber].style.color = "lightgreen";
                        } else {
                            // if answer is wrong or blank
                            // color the answers red
                            answerContainers[questionNumber].style.color = "red";
                        }
                    });

                    // show number of correct answers out of total
                    resultsContainer.innerHTML = `你答对了${myQuestions.length}中的${numCorrect}`;
                }

                function showSlide(n) {
                    slides[currentSlide].classList.remove("active-slide");
                    slides[n].classList.add("active-slide");
                    currentSlide = n;

                    if(currentSlide === 0) {
                        previousButton.style.display = "none";
                    } else {
                        previousButton.style.display = "inline-block";
                    }

                    if(currentSlide === slides.length - 1) {
                        nextButton.style.display = "none";
                        submitButton.style.display = "inline-block";
                    } else {
                        nextButton.style.display = "inline-block";
                        submitButton.style.display = "none";
                    }
                }

                function showNextSlide() {
                    showSlide(currentSlide + 1);
                }

                function showPreviousSlide() {
                    showSlide(currentSlide - 1);
                }

                const quizContainer = document.getElementById("quiz");
                const resultsContainer = document.getElementById("results");
                const submitButton = document.getElementById("submit");

                // display quiz right away
                buildQuiz();

                const previousButton = document.getElementById("previous");
                const nextButton = document.getElementById("next");
                const slides = document.querySelectorAll(".slide");
                let currentSlide = 0;

                showSlide(0);

                // on submit, show results
                submitButton.addEventListener("click", showResults);
                previousButton.addEventListener("click", showPreviousSlide);
                nextButton.addEventListener("click", showNextSlide);
            })();
        </script>
    </body>

</html>

### JavaScript实现选择后自动滚动到下一题功能 要实现当用户在一个选项中做出选择之后,页面能够自动滚动到下一个题目位置的功能,可以利用 `Element.scrollIntoView()` 方法来完成。以下是完整的解决方案: #### HTML结构示例 假设我们有一个简单的问卷表单,其中包含多个问题对应的选项。 ```html <div id="question-container"> <div class="question" id="q1"> <p>问题 1: 你喜欢的颜色是什么?</p> <select class="next-question-trigger"> <option value="">请选择</option> <option value="red">红色</option> <option value="blue">蓝色</option> <option value="green">绿色</option> </select> </div> <div class="question" id="q2" style="margin-top: 100vh;"> <p>问题 2: 你最喜欢的水果是什么?</p> <select class="next-question-trigger"> <option value="">请选择</option> <option value="apple">苹果</option> <option value="banana">香蕉</option> <option value="orange">橙子</option> </select> </div> <div class="question" id="q3" style="margin-top: 100vh;"> <p>问题 3: 你最喜欢的城市是哪里?</p> <select class="next-question-trigger"> <option value="">请选择</option> <option value="beijing">北京</option> <option value="shanghai">上海</option> <option value="guangzhou">广州</option> </select> </div> </div> ``` #### CSS样式 为了模拟较长的页面,这里设置了较大的`margin-top`值以便于测试滚动效果。 ```css .question { border: 1px solid #ccc; padding: 20px; } ``` #### JavaScript逻辑 下面是一个基于事件监听器的脚本,用于检测下拉框的选择变化并触发页面滚动至下一题。 ```javascript document.addEventListener('DOMContentLoaded', function () { const questions = document.querySelectorAll('.question'); const triggers = document.querySelectorAll('.next-question-trigger'); triggers.forEach((trigger, index) => { trigger.addEventListener('change', function () { if (index + 1 < questions.length) { // 确保不是最后一道题 const nextQuestion = questions[index + 1]; nextQuestion.scrollIntoView({ behavior: 'smooth' }); // 平滑滚动 } else { alert('已经是最后一个问题!'); } }); }); }); ``` 以上代码实现了以下功能: - 当用户在某个 `<select>` 下拉菜单中选择了任意一项时,会触发展开的 `change` 事件。 - 如果当前问题是最后一个,则弹窗提示;如果不是最后一个,则调用 `scrollIntoView` 将视图平滑滚动到下一个 `.question` 容器的位置[^1]。 --- ### 注意事项 1. **兼容性**:`scrollIntoView` 的 `{behavior: 'smooth'}` 参数可能不被部分旧版浏览器支持。如果需要更广泛的兼容性,可以通过第三方库(如 jQuery 或 Locomotive Scroll)替代原生方法。 2. **动态加载内容**:如果页面中的问题列表是由 AJAX 动态渲染出来的,则需调整初始化方式以适应异步更新后的 DOM 结构。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值