Swiper插件可用于PC端和移动端;是开源、免费、强大的触摸滑动插件。下面主要介绍其基本用法:
1.首先加载插件,需要用到的文件有swiper.min.js和swiper.min.css文件(可以在官网下载、CDN或者npm、yarn安装等)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>swiper的使用</title> 7 <link rel="stylesheet" href="./css/reset.css"> 8 <!--引入swiper.min.css--> 9 <link rel="stylesheet" href="./css/swiper.min.css"> 10 </head> 11 <body> 12 13 14 15 <!--引入swiper.min.js--> 16 <script src="./js/swiper.min.js"></script> 17 </body> 18 </html>
2.在HTML中定义一个swiper容器,并将内容放入到容器内
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>swiper的使用</title> 7 <link rel="stylesheet" href="./css/reset.css"> 8 <!--引入swiper.min.css--> 9 <link rel="stylesheet" href="./css/swiper.min.css"> 10 </head> 11 <body> 12 <div class="swiper_wrap"> 13 <div class="swiper-container"> 14 <div class="swiper-wrapper"> 15 <div class="swiper-slide"> 16 <img src="./image/a.jpg" alt=""> 17 </div> 18 <div class="swiper-slide"> 19 <img src="./image/b.jpg" alt=""> 20 </div> 21 <div class="swiper-slide"> 22 <img src="./image/c.jpg" alt=""> 23 </div> 24 </div> 25 <!-- 如果需要分页器 --> 26 <div class="swiper-pagination"></div> 27 28 <!-- 如果需要导航按钮 --> 29 <div class="swiper-button-prev"></div> 30 <div class="swiper-button-next"></div> 31 32 <!-- 如果需要滚动条 --> 33 <div class="swiper-scrollbar"></div> 34 </div> 35 </div> 36 <!--引入swiper.min.js--> 37 <script src="./js/swiper.min.js"></script> 38 </body> 39 </html>
3.根据需求可以给swiper设置样式,示例如下:
1 <style> 2 .swiper-container { 3 width: 600px; 4 height: 300px; 5 } 6 .swiper-slide img{ 7 width:100%; 8 height: 100%; 9 } 10 </style>
4.初始化swiper(所有参数都是可以根据需求个性化配置的)
1 <script> 2 var mySwiper = new Swiper ('.swiper-container', { 3 direction: 'vertical', // 垂直切换选项 4 loop: true, // 循环模式选项 5 6 // 如果需要分页器 7 pagination: { 8 el: '.swiper-pagination', 9 }, 10 11 // 如果需要前进后退按钮 12 navigation: { 13 nextEl: '.swiper-button-next', 14 prevEl: '.swiper-button-prev', 15 }, 16 17 // 如果需要滚动条 18 scrollbar: { 19 el: '.swiper-scrollbar', 20 }, 21 }) 22 </script>
完成以上基本的4个步骤之后,就能成功的运行页面啦!
Swiper5官网地址:https://www.swiper.com.cn/