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

Stimulus JS modal点击背景无法关闭仅Esc可关闭且模态框右移问题

问题原因
  • 事件冒泡冲突:你将modal容器嵌套在绑定了click触发逻辑的<button>元素内部,点击modal背景时,点击事件会向上冒泡到父级button,触发click->modal#open逻辑,相当于刚触发关闭就立刻重新打开了modal,视觉上就表现为modal小幅偏移、无法关闭。
  • 配置冲突:你添加了modal-disable-backdrop="true"属性禁用了组件默认的背景层,同时自定义CSS隐藏了#modal-background元素,导致背景点击的关闭逻辑无法正常触发。
修复步骤
  1. 移动modal容器位置,将其从<button>内部移出,放到当前页面层级的最外层,避免事件冒泡,参考修改后的代码:
%div
  -if annotations.empty?
    %p.text-2xl.text-primary-600.mt-2.text-center= t('views.doctor_portal.annotation_form.no_annotations')
  -else
    .text-center.text-xl.text-primary-600= t('views.doctor_portal.annotation_modal.header')
    .flex.flex-row.flex-wrap.border-2.border-gray-700.w-full.h-max.overflow-y-auto.justify-center.rounded{style: 'max-height: 14rem'}
      - annotations.each do |annotation|
        %button{ "data-action": "click->modal#open", "data-content": annotation.content, "data-date": I18n.locale == :en ? l(annotation.created_at, format: '%B %d %Y') : l(annotation.created_at, format: '%d %B, %Y') }
          .flex.flex-col.w-52.h-max.border-2.border-primary-500.m-1.p-1.rounded
            %div.text-center
              - if I18n.locale == :en
                #{l annotation.created_at, format: '%B %d %Y'}
              - else
                #{l annotation.created_at, format: '%d %B, %Y'}
            %div.text-center #{annotation.content[0..19]}(...)
    / modal容器移到循环外部,独立层级
    .hidden.animated.fadeIn.fixed.inset-0.overflow-y-auto.flex.items-center.justify-center{ data: { controller: "modal", "modal-allow-background-close": "true", action: "click->modal#closeBackground keyup@window->modal#closeWithKeyboard", "modal-target": "container" }}
      / Modal Inner Container
      .max-h-screen.w-full.max-w-lg.relative{ :style => "z-index: 9999;"}
        / Modal Card
        .m-1.rounded.shadow-2xl.bg-white.p-5
          .text-center.text-xl.text-primary-500= t('views.doctor_portal.annotation_modal.note')
          .text-center.p-2{ "data-modal-target": "annotationContent" }
          .text-center.text-xs.-mb-5= t('views.doctor_portal.annotation_modal.press_esc')
  1. 删除自定义CSS中隐藏#modal-background的代码,同时删除modal-disable-backdrop="true"属性,让组件自动管理背景层的显示隐藏。
  2. 新增少量modal控制器逻辑,点击按钮时将对应annotation的内容动态赋值到modal的内容展示节点即可适配多个annotation的展示需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:36:04