Swiper开启loop模式后重新进入首个slide时按钮点击事件失效问题
问题根因
Swiper的loop模式为了实现无缝滚动效果,会自动在真实slide列表的前后复制若干个相同的slide节点,这些复制出来的节点属于Swiper动态生成的,没有继承Angular模板中绑定的(click)事件,因此当滚动到复制生成的首尾slide时,点击按钮就不会触发对应方法。
解决方案
方案1:使用事件委托(最稳定,适配所有loop场景)
不给单个按钮绑定点击事件,改为在swiper外层容器绑定全局点击事件,通过事件冒泡判断点击目标是否为查看更多按钮,再获取对应项目数据即可。
代码示例:
首先调整模板代码:
<swiper #swiper [config]="configSlide" (click)="handleSwiperClick($event)"> <div *ngFor="let i of proyects.proyectsItems; let index = index" class="swiper-slide" [attr.data-project-index]="index"> <!-- 原有内容不变 --> <img class="project-img " [src]="i.imagesProyects[0]"> <button class="button-show-more"> Ver mas </button> <p class="textImageProject "> {{i.typeProyect}} </p> <!-- 原有内容不变 --> </div> </swiper>
然后在ts文件中新增事件处理方法:
handleSwiperClick(e: Event) { const target = e.target as HTMLElement; // 判断点击对象是否为查看更多按钮 if (target.classList.contains('button-show-more')) { // 获取当前slide对应的项目索引 const slideEl = target.closest('.swiper-slide') as HTMLElement; const projectIndex = Number(slideEl.dataset.projectIndex); const currentProject = this.proyects.proyectsItems[projectIndex]; // 调用原有打开模态框方法 this.openModalProyect(e, currentProject); } }
方案2:调整Swiper配置适配loop模式
如果不想修改事件绑定逻辑,可以在你的configSlide中新增以下配置,增强loop模式下节点的事件同步能力,适合slide数量不多的场景:
configSlide: SwiperOptions = { // 原有配置保持不变 navigation: { nextEl: '.rightPosition', prevEl: '.leftPosition' }, autoplay: { delay: 6000, disableOnInteraction: false }, breakpoints: { 320: { slidesPerView: 1, spaceBetween: 20 }, 576: { slidesPerView: 1.7, spaceBetween: -60 }, 770: { slidesPerView: 2, spaceBetween: -50 }, }, centeredSlides: true, loop: true, slideNextClass: 'swiper-slide-next', slidePrevClass: 'swiper-slide-prev', // 新增以下配置 loopAdditionalSlides: this.proyects.proyectsItems.length, // 预复制和真实slide数量一致的节点 observer: true, // 开启Swiper的DOM变动监听 observeParents: true, observeSlideChildren: true, }
内容的提问来源于stack exchange,提问作者Nicolas Garcia
相关产品推荐
相关产品推荐

