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