如何实现元素显隐:页面加载及点击按钮按顺序切换指定ID的Div
实现步骤与代码整合
1. 初始隐藏非start区块
先通过CSS默认隐藏start以外的所有div,确保页面加载时仅显示初始区块:
#a, #b, #c { /* 后续新增的字母类div都需追加到这里 */ display: none; }
2. 编写切换逻辑的JavaScript函数
定义全局变量记录当前显示的区块ID,再写切换函数处理隐藏/显示逻辑:
// 初始化当前显示区块为start let currentSection = "start"; function nextSection() { // 隐藏当前区块 document.getElementById(currentSection).style.display = "none"; // 计算下一个区块的ID if (currentSection === "start") { currentSection = "a"; } else { // 将当前字母转ASCII码+1,再转回字母 const nextCharCode = currentSection.charCodeAt(0) + 1; currentSection = String.fromCharCode(nextCharCode); } // 检查下一个区块是否存在 const nextSectionEl = document.getElementById(currentSection); if (nextSectionEl) { nextSectionEl.style.display = "block"; } else { // 无后续区块时,回到初始页(可按需修改逻辑) alert("所有内容已完成!"); document.getElementById("start").style.display = "block"; currentSection = "start"; } }
3. 给按钮绑定onclick事件
修改HTML,给启动按钮和各区块的正确选项按钮添加切换事件:
<div id="start"> Lets Begin<br /> <button id="startbutton" onclick="nextSection()">Start</button> </div> <div id="a"> <img onclick="play('sounds/apple.mp3')" src="images/apple.png" width="400" height="400" /> <br /> <button onclick="play('sounds/correct1.mp3'); nextSection()" class="multiple-choice"> Apple </button> <button onclick="play('sounds/wrong1.mp3')" class="multiple-choice"> Slinky </button> <button onclick="play('sounds/wrong1.mp3')" class="multiple-choice"> Orange </button> </div> <div id="b"> <img onclick="play('sounds/banana.mp3')" src="images/banana.png" width="400" height="400" /> <br /> <button onclick="play('sounds/wrong1.mp3')" class="multiple-choice">Monkey</button> <button onclick="play('sounds/correct1.mp3'); nextSection()" class="multiple-choice">Banana</button> <button onclick="play('sounds/wrong1.mp3')" class="multiple-choice">Yellow</button> </div>
逻辑说明
currentSection相当于PHP中的状态变量,用来追踪当前显示的区块。- 切换时先隐藏当前区块,再通过ASCII码计算下一个字母ID(start直接跳转a,a之后依次递推)。
- 正确选项按钮通过分号分隔,同时触发音效播放和区块切换。
- 若后续无对应ID的区块,会自动回到初始页,可根据需求调整这部分逻辑。
内容的提问来源于stack exchange,提问作者topdoller
相关产品推荐
相关产品推荐

