You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery点击关闭按钮移除父div类并隐藏自身失效问题

问题

我实现了点击div使其全屏展开的功能,展开后显示一个“关闭”按钮。点击该关闭按钮时,希望div恢复正常状态且按钮隐藏,但以下代码无法实现该效果,请问原因是什么?

代码片段

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="myDiv" id="myDiv">
  <button id="SaveNClose">&times Click to Save and Close</button>
  <div class="row">Main Text</div>
</div>

CSS

#SaveNClose {
  border: 1px solid black;
  background-color: red;
  border-radius: 50px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
}

.myDiv.fullscreen {
  z-index: 9999;
  width: 100%;
  height: 100%;
  position: fixed;
  text-align: center;
  align-items: center;
  top: 0;
  left: 0;
  background-color: #799C4B;
}

JS

$("#SaveNClose").hide(); // Hide the close button

$('#myDiv').click(function(e) {
  $(this).addClass('fullscreen');
  $("#SaveNClose").show();
});


$(document).ready(function() {
  $("#SaveNClose").click(function() {
    $("#myDiv").removeClass("fullscreen");
    $("#SaveNClose").hide();
  });
});

问题原因

核心问题是事件冒泡:关闭按钮是#myDiv的子元素,点击按钮时,事件会向上冒泡触发父元素#myDiv的点击事件。也就是说,点击按钮后,先执行按钮的回调(移除全屏类、隐藏按钮),紧接着又执行父div的回调(重新添加全屏类、显示按钮),最终视觉上没有任何变化。

另外还有一个规范问题:初始化隐藏按钮的代码写在了$(document).ready()外面,虽然jQuery加载后可能能找到元素,但存在DOM未加载完成时找不到元素的风险。

修复方案

  1. 在按钮的点击事件中添加e.stopPropagation(),阻止事件冒泡到父元素;
  2. 将所有JS逻辑移入$(document).ready()回调内,确保DOM加载完成后再执行操作。

修复后的JS代码:

$(document).ready(function() {
  $("#SaveNClose").hide(); // Hide the close button

  $('#myDiv').click(function(e) {
    $(this).addClass('fullscreen');
    $("#SaveNClose").show();
  });

  $("#SaveNClose").click(function(e) {
    e.stopPropagation(); // 阻止事件冒泡到父元素
    $("#myDiv").removeClass("fullscreen");
    $("#SaveNClose").hide();
  });
});

内容的提问来源于stack exchange,提问作者wing22yu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:50:41