使用swiper轮播插件,遇到三个问题
1 . 自带按钮,只能出现在轮播区域内 , 因为轮播盒子swiper-container设置了overflow:hidden
2 . 同屏显示多个轮播页 , 在宽度不同的的情况下,会出现收尾轮播页溢出被覆盖的情况
3 . (如果想留出空隙 , 给轮播加背景) , 无法给轮播盒子swiper-container设置padding , 会导致子轮播页显示不完整
<html lang="en">
<head>
<meta charset="utf-8">
<title>Swiper demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">
<link rel="stylesheet" href="./swiper/css/swiper.min.css">
<style>
html,
body {
position: relative;
width: 100%;
height: 100%;
}
body {
background: #eee;
margin: 0;
padding: 0;
}
.box {
width: 80%;
height: 50%;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
background: yellow;
}
.swiper-container {
width: 80%;
height: 100%;
transform: translateY(30%);
}
/* 按钮 */
.btn-left {
width: 40px;
height: 60px;
background: green;
position: absolute;
top: 40%;
left: -40px;
}
.btn-right {
width: 40px;
height: 60px;
background: green;
position: absolute;
top: 40%;
right: -40px;
left: auto;
}
/* 解决问题2 : 使用百分比 , 在js中进行配置 */
/* 其他屏,占比25% */
.swiper-slide {
width: 25%;
display: flex;
justify-content: center;
align-items: center;
box-sizing: border-box;
background: skyblue;
color: #fff;
}
/* 使用百分比,首屏(当前屏)占比48%--(考虑到两个1%的间距) */
.swiper-slide-active {
width: 48%;
transition: all 0.5s;
}
</style>
</head>
<body>
<!-- Swiper -->
<!-- 解决问题3 : 给轮播盒子加父盒子 , 给父盒子设置padding -->
<div class="box">
<!-- 解决问题1 : 定制按钮 加上swiper提供的两个类名即可 -->
<div class="btn-left swiper-button-prev"></div>
<div class="btn-right swiper-button-next"></div>
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
</div>
</div>
</div>
<!-- Swiper JS -->
<script src="./swiper/js/swiper.min.js"></script>
<script>
var swiper = new Swiper('.swiper-container', {
// 间距 1%
spaceBetween: '1%',
// 同屏显示几个轮播 , 'auto'根据宽度自动设定数量
// loop模式下如果设置为'auto'还需要设置另外一个参数loopedSlides
slidesPerView: 'auto',
//在loop模式下使用slidesPerview:'auto',需要loopedSlides
// 如果可视轮播为3,那么设置大于3即可
loopedSlides: 4,
loop: true,
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
</script>
</body>
</html>