如何不关闭模态框更改其内容?多按钮打开同一模态框不同内容问题
实现方案
核心逻辑调整
你只需要在触发按钮的点击逻辑里增加当前激活菜单的状态判断即可,不需要关闭已打开的模态框,直接切换内容容器的显隐状态即可实现需求。
步骤1:修复HTML小问题
你现有HTML里account-item和help-item的id重复了,id必须全局唯一,建议统一改成类名:
<!-- 把所有原来的 id="account-item" 改成 class="account-item menu-content" --> <!-- 把所有原来的 id="help-item" 改成 class="help-item menu-content" -->
步骤2:编写JS逻辑(替换你的setMenus.js内容即可)
// 获取DOM元素 const dropdownTogglers = document.querySelectorAll('.dropdown-toggler:not(#close-dropdown)'); const dropdownMenu = document.getElementById('dropdown-menu'); const closeBtn = document.getElementById('close-dropdown'); const menuContainers = document.querySelectorAll('.menu-container'); // 状态变量:记录当前激活的菜单id,初始为空 let currentActiveMenu = null; // 控制模态框显隐的类名,可根据你现有样式替换 const MENU_OPEN_CLASS = 'is-collapsed'; // 切换内容容器显隐 function showMenuContainer(menuId) { // 先隐藏所有内容容器 menuContainers.forEach(container => { container.classList.add('opacity-0'); container.classList.remove('opacity-1'); }); // 显示对应id的内容容器 const targetContainer = document.querySelector(`.${menuId}-container`); if(targetContainer) { targetContainer.classList.remove('opacity-0'); targetContainer.classList.add('opacity-1'); } } // 给两个触发按钮绑定点击事件 dropdownTogglers.forEach(toggler => { toggler.addEventListener('click', (e) => { const targetMenuId = e.currentTarget.id; // 判断模态框当前是否打开 const isMenuOpen = dropdownMenu.classList.contains(MENU_OPEN_CLASS); if(!isMenuOpen) { // 模态框未打开:打开模态框+显示对应内容 dropdownMenu.classList.add(MENU_OPEN_CLASS); showMenuContainer(targetMenuId); currentActiveMenu = targetMenuId; } else { // 模态框已打开 if(targetMenuId === currentActiveMenu) { // 点击的是当前激活的按钮:关闭模态框 dropdownMenu.classList.remove(MENU_OPEN_CLASS); currentActiveMenu = null; } else { // 点击的是另一个按钮:直接切换内容,无需关闭模态框 showMenuContainer(targetMenuId); currentActiveMenu = targetMenuId; } } }) }) // 关闭按钮逻辑 closeBtn.addEventListener('click', () => { dropdownMenu.classList.remove(MENU_OPEN_CLASS); currentActiveMenu = null; })
步骤3:CSS补充(如果现有样式缺少可新增)
.opacity-0 { opacity: 0; pointer-events: none; position: absolute; /* 避免两个内容容器互相占位 */ } .opacity-1 { opacity: 1; pointer-events: auto; position: relative; } /* 模态框显隐样式仅做示例,可根据你原有代码逻辑调整类名和属性 */ .dropdown-menu.is-not-collapsed { display: none; } .dropdown-menu.is-collapsed { display: block; }
内容的提问来源于stack exchange,提问作者Giuseppe Bruno
相关产品推荐
相关产品推荐

