UNPKG

zz-shopify-components

Version:

Reusable Shopify components for theme projects

117 lines (106 loc) 3.13 kB
class VersionDialog extends HTMLElement { isOpen = false; swiper = null; // swiper实例 constructor() { super(); this.init(); } init() { const dialog = this.querySelector('dialog'); if (dialog) { const observer = new MutationObserver(() => { if (dialog.open) { // 初始化swiper if (!this.swiper) { this.initSwiper(); } window.zzLockBodyScroll && window.zzLockBodyScroll(); } else { // 销毁swiper if (this.swiper) { this.destroySwiper(); } } }); // 监听dialog open observer.observe(dialog, { attributes: true }); // 添加关闭事件监听 dialog.addEventListener('close', () => { // 确保在关闭时销毁swiper if (this.swiper) { this.destroySwiper(); } window.zzUnlockBodyScroll && window.zzUnlockBodyScroll(); }); // 添加点击backdrop关闭的事件监听 dialog.addEventListener('click', (e) => { const dialogDimensions = dialog.getBoundingClientRect(); if ( e.clientX < dialogDimensions.left || e.clientX > dialogDimensions.right || e.clientY < dialogDimensions.top || e.clientY > dialogDimensions.bottom ) { dialog.close(); } }); } } // 初始化 initSwiper() { const swiperContainer = this.querySelector('.swiper'); if (swiperContainer) { const slides = swiperContainer.querySelectorAll('.swiper-slide'); const imageCount = slides.length; this.swiper = new Swiper(swiperContainer, { slidesPerView: 1, spaceBetween: 0, pagination: { el: this.querySelector('.swiper-pagination'), type: 'bullets', clickable: true, dynamicBullets: false, }, navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, effect: 'slide', fadeEffect: { crossFade: true, }, loop: imageCount > 1, observer: true, observeParents: true, speed: 500, on: { init: function () { const paginationEl = this.pagination.el; const prevButton = swiperContainer.querySelector( '.swiper-button-prev' ); const nextButton = swiperContainer.querySelector( '.swiper-button-next' ); if (imageCount <= 1) { if (paginationEl) paginationEl.style.display = 'none'; if (prevButton) prevButton.style.display = 'none'; if (nextButton) nextButton.style.display = 'none'; } }, }, }); } } // 销毁 destroySwiper() { if (this.swiper) { // 完全销毁swiper,包括所有事件监听器和DOM元素 this.swiper.destroy(true, true); this.swiper = null; } } } if (!customElements.get('version-dialog')) { customElements.define('version-dialog', VersionDialog); }