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

如何在登录模态框内打开忘记密码模态框并解决自动关闭问题

问题原因

  • 核心原因:登录模态框内的「忘记密码」是<a>标签,href属性为空,点击后会触发浏览器默认的页面重载行为,页面刷新后刚弹出的忘记密码模态框直接消失,看起来就是秒关。
  • 隐藏问题:你连续两次给window.onclick赋值,后面的赋值会覆盖前一次的逻辑,最终只有忘记密码模态框的「点击外部关闭」逻辑生效,登录模态框的外部关闭功能会失效。
  • 次要诱因:点击忘记密码链接的事件会向上冒泡到window层,可能触发模态框的外部关闭判断,导致刚弹出的模态框被误关。

修复方案

修改你的JS逻辑如下即可:

// Get the modal
var modal = document.getElementById("loginModal");
var modal2 = document.getElementById("registerModal");
var modal3 = document.getElementById("forgetPasswordModal");

// Get the button that opens the modal
var btn = document.getElementById("login");
var btn3 = document.getElementById("forgetPassword");

// Get the <span> element that closes the modal
var span = document.getElementById("close");
var span3 = document.getElementById("close3");

// When the user clicks the button, open the modal
btn.onclick = function () {
  modal.style.display = "block";
};
btn3.onclick = function (e) {
  // 阻止a标签默认跳转刷新
  e.preventDefault();
  // 阻止事件冒泡避免触发window的点击关闭逻辑
  e.stopPropagation();
  // 可选:关闭登录模态框,避免两个模态框重叠
  modal.style.display = "none";
  modal3.style.display = "block";
};

// When the user clicks on <span> (x), close the modal
span.onclick = function () {
  modal.style.display = "none";
};
span3.onclick = function () {
  modal3.style.display = "none";
};
// 合并两个模态框的外部关闭逻辑,不要重复赋值window.onclick
window.onclick = function (event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
  if (event.target == modal3) {
    modal3.style.display = "none";
  }
};

额外优化建议

你当前忘记密码模态框内的邮箱输入框id="loginEmail"和登录模态框内的邮箱输入框id重复,后续如果要通过id获取输入值会出现异常,建议修改为唯一id,比如id="forgetEmail"。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:27:02