如何实现父按钮点击展示子按钮、子按钮点击切换图片的交互功能
问题修复方案
以下是针对你的需求的完整修复内容:
现存问题点
- 第一个顶部按钮绑定的子容器ID为
expamle1,但实际对应子容器的ID是exp,ID不匹配导致子按钮点击后无法触发预期效果 - 没有编写点击新的顶部按钮时关闭其他已打开子容器的逻辑,导致多个子按钮组同时展示
- 未给子按钮容器设置默认隐藏样式,容器高度变化会触发页面滚动
修复后完整代码
样式部分(添加到页面<head>的<style>标签内)
/* 子按钮容器默认隐藏,统一设置间距 */ .sub-btn-group { display: none; margin: 12px 0; }
JS代码部分
// 复用图片切换逻辑,不用重复定义多个相似函数 function changeImg(imgPath) { document.getElementById('myImage').src = imgPath; } // 切换子按钮组显示状态 function toggleSubGroup(targetId) { // 先关闭所有子按钮组 const allSubGroups = document.querySelectorAll('.sub-btn-group'); allSubGroups.forEach(item => { item.style.display = 'none'; }); // 打开当前点击对应的子按钮组 document.getElementById(targetId).style.display = 'block'; }
HTML代码部分
<center> <img id="myImage" src="/Users/Hp/Desktop/booo/bo99856/gtR.png" width="750px" height="auto"> <!-- 第一个顶部按钮X --> <button type="button" onclick="toggleSubGroup('expamle1')"> <img src="/Users/Hp/Desktop/booo/bo99856/btktR.png" width="35px" height="35px"><br><br>Dfl-6127 </button> <!-- 统一添加sub-btn-group类名,修正ID与按钮绑定的一致 --> <div id="expamle1" class="sub-btn-group"> <button class="button30" onclick="changeImg('/Users/Hp/Desktop/booo/bo99856/bb0r.png')"> <img src="/Users/Hp/Desktop/booo/bo99856/bb0r.png" width="35px" height="35px"><br> </button> <button class="button16" onclick="changeImg('/Users/Hp/Desktop/booo/Ff95y/btkt5R.png')"> <img src="/Users/Hp/Desktop/booo/Ff95y/btkt5R.png" width="35px" height="35px"><br> </button> <button class="button21" onclick="changeImg('/Users/Hp/Desktop/booo/Ff95y/frknk.png')"> <img src="/Users/Hp/Desktop/booo/Ff95y/frknk.png" width="35px" height="35px"><br> </button> </div> <!-- 第二个顶部按钮Y --> <button type="button" id="buton22" onclick="toggleSubGroup('expamle2')"> <img src="/Users/Hp/Desktop/booo/bo99856/btktR.png" width="35px" height="35px"><br><br>Dyb-9599 </button> <div id="expamle2" class="sub-btn-group"> <button class="button19 " onclick="changeImg('/Users/Hp/Desktop/booo/Ff95y/kmanha.png')"> <img src="/Users/Hp/Desktop/booo/Ff95y/kmanha.png" width="35px" height="35px"><br><br>KM-HA8 </button> <button class="button20 " onclick="changeImg('/Users/Hp/Desktop/booo/Ff95y/rylean5.png')"> <img src="/Users/Hp/Desktop/booo/Ff95y/rylean5.png" width="35px" height="35px"><br><br>RY-5 </button> <button class="button21 " onclick="changeImg('/Users/Hp/Desktop/booo/Ff95y/88793cg.png')"> <img src="/Users/Hp/Desktop/booo/Ff95y/88793cg.png" width="35px" height="35px"><br><br>88-93 </button> </div> </center>
内容的提问来源于stack exchange,提问作者55552408k
相关产品推荐
相关产品推荐

