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

Packery布局下点击链接开模态框不触发父元素折叠问题求助

解决Packery布局中点击链接触发父元素折叠的问题

我完全懂你现在的困扰——好不容易展开的卡片,点里面的链接打开模态框的同时,卡片居然又缩回去了,确实让人头大。问题的核心是事件冒泡:点击链接时,事件会向上传递到父级的.expand元素,触发了它的点击逻辑(折叠卡片+Packery重新布局)。

之前你尝试stopPropagation却禁用了模态框,应该是没找对阻止冒泡的时机。正确的思路是:只阻止链接的点击事件向上冒泡到父元素,同时保留模态框的触发逻辑。

修改后的JavaScript代码

$(document).ready(function(){ 
  var $grid = $('.grid').packery({ 
    itemSelector: '.grid-item', 
  }); 

  // 卡片展开/折叠逻辑
  $grid.on( 'click', '.expand', function( event ) { 
    $( event.currentTarget ).toggleClass('grid-item--large'); 
    $grid.packery('layout'); 
    $(this).children('.hiddenInfo').toggle(); 
  }); 

  // 阻止链接点击事件冒泡到父元素,避免触发折叠
  $grid.on('click', '.hiddenInfo a', function(event) {
    event.stopPropagation(); 
    // jquery-modal会自动处理rel="modal:open"的逻辑,无需额外触发
  });
});

为什么这样可行?

  • 点击链接时,event.stopPropagation()会切断事件向上传递的路径,不会触发.expand元素的折叠逻辑,卡片就能保持展开状态。
  • jquery-modal的模态框触发逻辑是直接绑定在链接上的(通过rel="modal:open"属性),不会被stopPropagation影响,模态框依然能正常打开。
  • 关闭模态框时,没有触发任何折叠卡片的事件,所以卡片会维持展开状态。

完整代码示例

HTML

<div class="container"> 
  <div class="grid"> 
    <div class="grid-item"> 
      <div class="grid-item-content expand"> 
        <div class="hiddenInfo"> 
          <a href="#openModalLink" rel="modal:open"><img src="img/thumb.jpg"/></a> 
        </div> 
      </div> 
    </div> 
  </div> 
</div> 
<div id="openModalLink" class="modal"> 
  <p>Some content in the modal</p> 
</div>

CSS

.container { 
  padding: 50px 0 30px 0; 
  display: block; 
  width: 98vw; 
} 
.grid { width: 100%; } 
.grid:after { 
  content: ''; 
  display: block; 
  clear: both; 
} 
.hiddenInfo { display: none; } 
.expand { 
  display: block; 
  z-index: 999; 
  width: 150px; 
  height: 150px; 
  background: #ffffff; 
} 
.expand:hover { cursor: pointer; } 
.grid-item-content { 
  width: 150px; 
  height: 150px; 
  border: 1px solid black; 
} 
.grid-item { 
  float: left; 
  padding: 4px; 
} 
.grid-item--large { 
  width: 520px; 
  height: 375px !important; 
  border-radius: 0 !important; 
  background-color: #ffffff; 
}

这样修改后,就能完美实现你想要的流程:

  1. 点击卡片 → 展开并显示链接
  2. 点击链接 → 打开模态框,卡片保持展开
  3. 关闭模态框 → 卡片依然展开

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:32:41