使用Alpine JS在Photoswipe灯箱外部添加按钮打开首张图片
实现需求
已为SwiperJS画廊配置Photoswipe Lightbox灯箱插件,需要在lightbox-wrapper容器外部新增基于Alpine JS的控制按钮,实现无论当前画廊停在哪张幻灯片,点击按钮都直接打开画廊第一张图片的交互。
现有代码
画廊渲染与灯箱绑定代码
<div class="swiper-wrapper lightbox"> <?php $i = 0; foreach( $gallery as $image_id ): $i++?> <?php $img_info = wp_get_attachment_image_src($image_id, 'full');?> <a <?php if($i == 1) { echo 'x-ref="firstSlide"'; } ?> href="<?= wp_get_attachment_image_url( $image_id, $size ); ?>" class="relative w-full h-full hover:cursor-pointer aspect-vertical swiper-slide" data-pswp-width="<?= $img_info[1]; ?>" data-pswp-height="<?= $img_info[2]; ?>" target="_blank"> <?= wp_get_attachment_image( $image_id, $size_medium, false, array('class' => 'object-cover w-full h-full ' . $rounded_elements)); ?> </a> <?php endforeach; ?> </div>
计划使用的触发按钮代码
<button class="absolute z-50 bottom-12 right-12 flex items-center justify-center opacity-80 hover:opacity-100 transition w-10 h-10 bg-white <?= $rounded_buttons; ?> shadow-md md:w-14 md:h-14 text-primary-dark"> <i class="icon-resize-full-alt"></i> </button>
实现方案
核心逻辑:现有代码已经给第一张幻灯片加了x-ref="firstSlide"的DOM引用,只需要保证按钮和画廊在同一个Alpine作用域下,给按钮绑定点击事件触发首张幻灯片的默认点击行为,就能直接复用Photoswipe原有灯箱触发逻辑,不需要额外调用API,也不会和现有交互冲突。
具体修改步骤
- 给画廊和按钮的共同父级添加Alpine作用域(如果二者已经在同一个带
x-data的容器内可跳过这步) - 给按钮添加
@click="$refs.firstSlide.click()"事件绑定,点击时模拟触发第一张幻灯片的点击操作,直接打开首张图的灯箱
修改后完整代码
<!-- 共同父级容器,初始化Alpine作用域,需要保留定位效果可给该容器加class="relative" --> <div x-data> <div class="swiper-wrapper lightbox"> <?php $i = 0; foreach( $gallery as $image_id ): $i++?> <?php $img_info = wp_get_attachment_image_src($image_id, 'full');?> <a <?php if($i == 1) { echo 'x-ref="firstSlide"'; } ?> href="<?= wp_get_attachment_image_url( $image_id, $size ); ?>" class="relative w-full h-full hover:cursor-pointer aspect-vertical swiper-slide" data-pswp-width="<?= $img_info[1]; ?>" data-pswp-height="<?= $img_info[2]; ?>" target="_blank"> <?= wp_get_attachment_image( $image_id, $size_medium, false, array('class' => 'object-cover w-full h-full ' . $rounded_elements)); ?> </a> <?php endforeach; ?> </div> <!-- 修改后的触发按钮,直接放在父容器内即可,无需嵌入lightbox-wrapper内部 --> <button @click="$refs.firstSlide.click()" class="absolute z-50 bottom-12 right-12 flex items-center justify-center opacity-80 hover:opacity-100 transition w-10 h-10 bg-white <?= $rounded_buttons; ?> shadow-md md:w-14 md:h-14 text-primary-dark"> <i class="icon-resize-full-alt"></i> </button> </div>
注意:按钮的
absolute定位会相对于最近的非static定位父级生效,如果按钮放在lightbox-wrapper外出现定位偏移,给上面新增的父级容器加class="relative"即可保持原有定位效果。
内容的提问来源于stack exchange,提问作者Rvervuurt
相关产品推荐
相关产品推荐

