使用jQuery+TailwindCSS实现消息/通知框互斥显示:打开一个隐藏其他
问题原因
你写的弹窗互斥判断逻辑仅在页面加载完成时执行一次,后续点击图标触发弹窗切换时不会触发该判断,因此无法实现关闭已打开弹窗的效果。
修正方案
你可以在每次点击弹窗触发按钮时,先隐藏所有其他弹窗,再切换当前点击对应的弹窗状态即可,以下是修改后的JS代码:
$(document).ready(function () { $("#messageIcon").on("click", function () { $("#notificationBox").fadeOut(); $("#messageBox").fadeToggle(); }); $("#notificationIcon").on("click", function () { $("#messageBox").fadeOut(); $("#notificationBox").fadeToggle(); }); });
可扩展优化方案
如果后续你可能新增更多弹窗,建议给所有弹窗容器添加统一类名popup-box,给触发图标添加data-target属性关联对应弹窗ID,不需要为每个弹窗单独写点击事件:
修改后的HTML代码:
<div class="relative"> <i id="messageIcon" data-target="#messageBox" data-message="6" class="fa fa-envelope cursor-pointer icon"></i> <div id="messageBox" class="popup-box absolute top-full left-0 mt-4 bg-white shadow-2xl text-black p-4" style="display: none;"> hello world </div> </div> <div class="relative"> <i id="notificationIcon" data-target="#notificationBox" data-notification="3" class="fa fa-bell cursor-pointer icon"></i> <div id="notificationBox" class="popup-box absolute top-full left-0 mt-4 bg-white shadow-2xl text-black p-4" style="display: none;"> hello world </div> </div>
对应的简化JS代码:
$(document).ready(function () { $(".icon").on("click", function () { const targetPopup = $(this).data("target"); // 隐藏所有非当前目标的弹窗 $(".popup-box").not(targetPopup).fadeOut(); // 切换当前目标弹窗状态 $(targetPopup).fadeToggle(); }); });
这种写法后续新增弹窗时,只要给对应图标加data-target属性、给弹窗加popup-box类即可,不需要额外修改JS逻辑。
内容的提问来源于stack exchange,提问作者user14201902
相关产品推荐
相关产品推荐

