首页 > 科技知识 > 科技数码 >

📚✨ JS小技巧 | 实现上一题下一题的趣味功能!💡

发布时间:2025-04-08 14:36:57来源:

在日常开发中,我们经常需要处理列表循环切换的需求,比如在线考试、问卷调查或产品展示。今天分享一个简单又实用的小功能:通过点击按钮实现上一题和下一题的无缝切换,同时让列表循环滚动起来!🚀

首先,准备好你的HTML结构,创建一个包含问题列表的`

    `标签,以及两个按钮分别用于“上一题”和“下一题”。接着用JavaScript监听按钮点击事件,动态调整当前显示的索引值。当索引超出范围时,利用模运算(`%`)让其回到列表开头,轻松实现循环效果!👇

    ```javascript

    let currentIndex = 0;

    const questions = document.querySelectorAll('li');

    const prevBtn = document.querySelector('prev');

    const nextBtn = document.querySelector('next');

    prevBtn.addEventListener('click', () => {

    currentIndex = (currentIndex - 1 + questions.length) % questions.length;

    showQuestion();

    });

    nextBtn.addEventListener('click', () => {

    currentIndex = (currentIndex + 1) % questions.length;

    showQuestion();

    });

    function showQuestion() {

    questions.forEach((q, index) => q.style.display = index === currentIndex ? 'block' : 'none');

    }

    ```

    🎉 有了这段代码,你的页面就能像魔法一样流畅切换题目了!无论是学习还是娱乐,都能带来更好的交互体验哦~快来试试吧!🎯✨

    免责声明:本答案或内容为用户上传,不代表本网观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。 如遇侵权请及时联系本站删除。