首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >使用swiper.js做一个分页滚动的封装组件

使用swiper.js做一个分页滚动的封装组件

原创
作者头像
程序员老彭
发布2025-10-15 14:40:18
发布2025-10-15 14:40:18
2070
举报
文章被收录于专栏:Java开发Java开发

我将为您创建一个基于Swiper.js的分页滚动封装组件,这个组件将具有良好的可复用性和配置灵活性,同时保持现代美观的UI设计。

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Swiper分页滚动组件</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入Swiper CSS -->
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
    
    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        neutral: '#F3F4F6',
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .swiper-button-custom {
                @apply w-10 h-10 rounded-full bg-white/80 backdrop-blur-sm flex items-center justify-center shadow-md transition-all duration-300 hover:bg-white hover:scale-110;
            }
            .pagination-bullet {
                @apply w-2.5 h-2.5 rounded-full transition-all duration-300;
            }
            .pagination-bullet-active {
                @apply w-8 bg-primary;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800 min-h-screen p-4 md:p-8">
    <div class="max-w-6xl mx-auto">
        <header class="mb-12 text-center">
            <h1 class="text-[clamp(1.8rem,4vw,2.8rem)] font-bold text-gray-900 mb-3">Swiper分页滚动组件</h1>
            <p class="text-gray-600 max-w-2xl mx-auto">一个高度可定制的Swiper分页滚动组件,支持自动播放、导航按钮、自定义分页器和多种滚动模式</p>
        </header>
        
        <!-- 示例1: 基础图片轮播 -->
        <section class="mb-16 bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6 border-b">
                <h2 class="text-xl font-semibold">基础图片轮播</h2>
                <p class="text-gray-500 text-sm">支持自动播放和分页导航</p>
            </div>
            <div class="p-4 md:p-6">
                <div class="swiper-container" id="imageSwiper" data-config='{
                    "slidesPerView": 1,
                    "spaceBetween": 0,
                    "loop": true,
                    "autoplay": {
                        "delay": 3000
                    },
                    "pagination": true,
                    "navigation": true,
                    "effect": "slide"
                }'>
                    <div class="swiper-wrapper">
                        <div class="swiper-slide">
                            <img src="https://picsum.photos/1200/500?random=1" alt="风景照片1" class="w-full h-[300px] md:h-[400px] object-cover rounded-lg">
                        </div>
                        <div class="swiper-slide">
                            <img src="https://picsum.photos/1200/500?random=2" alt="风景照片2" class="w-full h-[300px] md:h-[400px] object-cover rounded-lg">
                        </div>
                        <div class="swiper-slide">
                            <img src="https://picsum.photos/1200/500?random=3" alt="风景照片3" class="w-full h-[300px] md:h-[400px] object-cover rounded-lg">
                        </div>
                        <div class="swiper-slide">
                            <img src="https://picsum.photos/1200/500?random=4" alt="风景照片4" class="w-full h-[300px] md:h-[400px] object-cover rounded-lg">
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 示例2: 卡片轮播 -->
        <section class="mb-16 bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6 border-b">
                <h2 class="text-xl font-semibold">卡片轮播</h2>
                <p class="text-gray-500 text-sm">多列显示,支持触摸滑动</p>
            </div>
            <div class="p-4 md:p-6">
                <div class="swiper-container" id="cardSwiper" data-config='{
                    "slidesPerView": "auto",
                    "spaceBetween": 20,
                    "loop": false,
                    "pagination": true,
                    "navigation": true,
                    "breakpoints": {
                        "640": {
                            "slidesPerView": 2
                        },
                        "1024": {
                            "slidesPerView": 3
                        }
                    }
                }'>
                    <div class="swiper-wrapper">
                        <div class="swiper-slide w-[280px] bg-neutral rounded-lg overflow-hidden shadow-sm">
                            <img src="https://picsum.photos/400/200?random=10" alt="产品图片1" class="w-full h-48 object-cover">
                            <div class="p-4">
                                <h3 class="font-medium text-lg mb-2">产品名称 1</h3>
                                <p class="text-gray-600 text-sm mb-3">这是产品的简短描述信息,展示产品的主要特点和优势。</p>
                                <button class="w-full py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">查看详情</button>
                            </div>
                        </div>
                        <div class="swiper-slide w-[280px] bg-neutral rounded-lg overflow-hidden shadow-sm">
                            <img src="https://picsum.photos/400/200?random=11" alt="产品图片2" class="w-full h-48 object-cover">
                            <div class="p-4">
                                <h3 class="font-medium text-lg mb-2">产品名称 2</h3>
                                <p class="text-gray-600 text-sm mb-3">这是产品的简短描述信息,展示产品的主要特点和优势。</p>
                                <button class="w-full py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">查看详情</button>
                            </div>
                        </div>
                        <div class="swiper-slide w-[280px] bg-neutral rounded-lg overflow-hidden shadow-sm">
                            <img src="https://picsum.photos/400/200?random=12" alt="产品图片3" class="w-full h-48 object-cover">
                            <div class="p-4">
                                <h3 class="font-medium text-lg mb-2">产品名称 3</h3>
                                <p class="text-gray-600 text-sm mb-3">这是产品的简短描述信息,展示产品的主要特点和优势。</p>
                                <button class="w-full py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">查看详情</button>
                            </div>
                        </div>
                        <div class="swiper-slide w-[280px] bg-neutral rounded-lg overflow-hidden shadow-sm">
                            <img src="https://picsum.photos/400/200?random=13" alt="产品图片4" class="w-full h-48 object-cover">
                            <div class="p-4">
                                <h3 class="font-medium text-lg mb-2">产品名称 4</h3>
                                <p class="text-gray-600 text-sm mb-3">这是产品的简短描述信息,展示产品的主要特点和优势。</p>
                                <button class="w-full py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">查看详情</button>
                            </div>
                        </div>
                        <div class="swiper-slide w-[280px] bg-neutral rounded-lg overflow-hidden shadow-sm">
                            <img src="https://picsum.photos/400/200?random=14" alt="产品图片5" class="w-full h-48 object-cover">
                            <div class="p-4">
                                <h3 class="font-medium text-lg mb-2">产品名称 5</h3>
                                <p class="text-gray-600 text-sm mb-3">这是产品的简短描述信息,展示产品的主要特点和优势。</p>
                                <button class="w-full py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">查看详情</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <!-- 示例3: 文字内容轮播 -->
        <section class="mb-16 bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="p-6 border-b">
                <h2 class="text-xl font-semibold">文字内容轮播</h2>
                <p class="text-gray-500 text-sm">使用fade效果的内容轮播</p>
            </div>
            <div class="p-4 md:p-6">
                <div class="swiper-container" id="textSwiper" data-config='{
                    "slidesPerView": 1,
                    "spaceBetween": 30,
                    "loop": true,
                    "autoplay": {
                        "delay": 4000
                    },
                    "pagination": true,
                    "navigation": true,
                    "effect": "fade"
                }'>
                    <div class="swiper-wrapper">
                        <div class="swiper-slide p-6 bg-neutral rounded-lg">
                            <div class="flex items-start mb-4">
                                <div class="text-primary text-3xl mr-4">
                                    <i class="fa fa-quote-left"></i>
                                </div>
                                <h3 class="text-xl font-semibold">用户评价 1</h3>
                            </div>
                            <p class="text-gray-700 mb-6 pl-12">这是一段用户评价内容,展示了用户对产品或服务的使用体验和满意度。用户认为该产品在多个方面表现出色,特别是在易用性和性能方面给与了高度评价。</p>
                            <div class="flex items-center pl-12">
                                <img src="https://picsum.photos/60/60?random=20" alt="用户头像" class="w-12 h-12 rounded-full object-cover mr-3">
                                <div>
                                    <p class="font-medium">张先生</p>
                                    <p class="text-sm text-gray-500">产品经理</p>
                                </div>
                            </div>
                        </div>
                        <div class="swiper-slide p-6 bg-neutral rounded-lg">
                            <div class="flex items-start mb-4">
                                <div class="text-primary text-3xl mr-4">
                                    <i class="fa fa-quote-left"></i>
                                </div>
                                <h3 class="text-xl font-semibold">用户评价 2</h3>
                            </div>
                            <p class="text-gray-700 mb-6 pl-12">这是另一段用户评价内容,详细描述了使用过程中的感受和发现的优点。用户特别提到了客服团队的专业服务和快速响应,这让他们的使用体验更加愉快。</p>
                            <div class="flex items-center pl-12">
                                <img src="https://picsum.photos/60/60?random=21" alt="用户头像" class="w-12 h-12 rounded-full object-cover mr-3">
                                <div>
                                    <p class="font-medium">李女士</p>
                                    <p class="text-sm text-gray-500">设计师</p>
                                </div>
                            </div>
                        </div>
                        <div class="swiper-slide p-6 bg-neutral rounded-lg">
                            <div class="flex items-start mb-4">
                                <div class="text-primary text-3xl mr-4">
                                    <i class="fa fa-quote-left"></i>
                                </div>
                                <h3 class="text-xl font-semibold">用户评价 3</h3>
                            </div>
                            <p class="text-gray-700 mb-6 pl-12">这是第三段用户评价,分享了长期使用该产品的体验和效果。用户表示产品的稳定性和持续更新让他们非常满意,并已经推荐给了同事和朋友使用。</p>
                            <div class="flex items-center pl-12">
                                <img src="https://picsum.photos/60/60?random=22" alt="用户头像" class="w-12 h-12 rounded-full object-cover mr-3">
                                <div>
                                    <p class="font-medium">王先生</p>
                                    <p class="text-sm text-gray-500">开发者</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- 引入Swiper JS -->
    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    
    <script>
        // Swiper组件封装类
        class SwiperComponent {
            /**
             * 构造函数
             * @param {string} containerId - 容器元素ID
             * @param {object} customConfig - 自定义配置
             */
            constructor(containerId, customConfig = {}) {
                this.container = document.getElementById(containerId);
                if (!this.container) {
                    console.error(`未找到ID为${containerId}的容器元素`);
                    return;
                }
                
                // 获取数据配置
                const dataConfig = this.container.dataset.config ? JSON.parse(this.container.dataset.config) : {};
                
                // 合并默认配置和用户配置
                this.config = {
                    ...this.getDefaultConfig(),
                    ...dataConfig,
                    ...customConfig
                };
                
                // 创建导航和分页元素
                this.createNavigation();
                this.createPagination();
                
                // 初始化Swiper
                this.initSwiper();
            }
            
            /**
             * 获取默认配置
             * @returns {object} 默认配置对象
             */
            getDefaultConfig() {
                return {
                    slidesPerView: 1,
                    spaceBetween: 10,
                    loop: false,
                    speed: 500,
                    pagination: false,
                    navigation: false,
                    autoplay: false,
                    effect: 'slide'
                };
            }
            
            /**
             * 创建导航按钮
             */
            createNavigation() {
                if (this.config.navigation) {
                    // 创建前向按钮
                    this.prevButton = document.createElement('div');
                    this.prevButton.className = 'swiper-button-prev swiper-button-custom absolute left-2 top-1/2 -translate-y-1/2 z-10';
                    this.prevButton.innerHTML = '<i class="fa fa-chevron-left text-primary"></i>';
                    
                    // 创建后向按钮
                    this.nextButton = document.createElement('div');
                    this.nextButton.className = 'swiper-button-next swiper-button-custom absolute right-2 top-1/2 -translate-y-1/2 z-10';
                    this.nextButton.innerHTML = '<i class="fa fa-chevron-right text-primary"></i>';
                    
                    // 添加到容器
                    this.container.appendChild(this.prevButton);
                    this.container.appendChild(this.nextButton);
                    
                    // 更新配置
                    this.config.navigation = {
                        prevEl: this.prevButton,
                        nextEl: this.nextButton
                    };
                }
            }
            
            /**
             * 创建分页器
             */
            createPagination() {
                if (this.config.pagination) {
                    // 创建分页容器
                    this.paginationContainer = document.createElement('div');
                    this.paginationContainer.className = 'swiper-pagination flex justify-center space-x-2 mt-6';
                    
                    // 添加到容器
                    this.container.appendChild(this.paginationContainer);
                    
                    // 更新配置
                    this.config.pagination = {
                        el: this.paginationContainer,
                        clickable: true,
                        renderBullet: (index, className) => {
                            return `<span class="${className} pagination-bullet bg-gray-300"></span>`;
                        },
                        bulletActiveClass: 'pagination-bullet-active'
                    };
                }
            }
            
            /**
             * 初始化Swiper实例
             */
            initSwiper() {
                // 设置容器样式
                this.container.style.position = 'relative';
                
                // 初始化Swiper
                this.instance = new Swiper(this.container, this.config);
            }
            
            /**
             * 滑动到指定索引
             * @param {number} index - 索引值
             * @param {number} speed - 动画速度
             */
            slideTo(index, speed = 300) {
                if (this.instance) {
                    this.instance.slideTo(index, speed);
                }
            }
            
            /**
             * 滑动到下一页
             */
            slideNext() {
                if (this.instance) {
                    this.instance.slideNext();
                }
            }
            
            /**
             * 滑动到上一页
             */
            slidePrev() {
                if (this.instance) {
                    this.instance.slidePrev();
                }
            }
            
            /**
             * 销毁Swiper实例
             */
            destroy() {
                if (this.instance) {
                    this.instance.destroy();
                }
                
                // 移除创建的元素
                if (this.prevButton && this.nextButton) {
                    this.container.removeChild(this.prevButton);
                    this.container.removeChild(this.nextButton);
                }
                
                if (this.paginationContainer) {
                    this.container.removeChild(this.paginationContainer);
                }
            }
        }
        
        // 页面加载完成后初始化所有Swiper组件
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化图片轮播
            const imageSwiper = new SwiperComponent('imageSwiper');
            
            // 初始化卡片轮播
            const cardSwiper = new SwiperComponent('cardSwiper');
            
            // 初始化文字内容轮播
            const textSwiper = new SwiperComponent('textSwiper');
            
            // 可以通过实例调用方法,例如:
            // setTimeout(() => {
            //     imageSwiper.slideTo(2);
            // }, 3000);
        });
    </script>
</body>
</html>
    

这个Swiper分页滚动封装组件具有以下特点:

  1. 封装性强:通过SwiperComponent类封装了Swiper的核心功能,提供简洁的API接口。
  2. 高度可配置
    • 支持通过data-config属性设置JSON配置
    • 也可以通过JavaScript参数进行配置
    • 支持所有Swiper原生配置项(如自动播放、循环、切换效果等)
  3. 响应式设计
    • 自适应不同屏幕尺寸
    • 可通过breakpoints配置不同尺寸下的显示效果
  4. 自定义UI
    • 美化的导航按钮(带有悬停动画效果)
    • 自定义分页指示器(激活状态有长度变化动画)
    • 符合现代设计美学的配色方案
  5. 多种使用场景
    • 图片轮播(示例1)
    • 卡片滑动展示(示例2)
    • 文字内容轮播(示例3)
  6. 易用的API
    • slideTo(index):滑动到指定索引
    • slideNext():滑动到下一页
    • slidePrev():滑动到上一页
    • destroy():销毁实例

使用方法非常简单,只需创建一个容器元素,设置好配置和内容,然后通过new SwiperComponent(containerId)即可初始化。您可以根据实际需求调整配置参数,实现各种滑动效果。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档