最近移动端项目中遇到一个滑动刻度功能,找了2个组件,都不能满足需求,想要改动一波,代码太糟糕(都莫得注释),无处下手。。。。越改越糟,就放弃了,自己来写。最后用swiper完成了这个功能。
代码如下:
swiper官网地址:https://www.swiper.com.cn/demo/index.html
scale.html
该demo中我默认生成了100个刻度,如果需要计算每个刻度代表的数值,可以在slideChange事件中通过 mySwiper.activeIndex计算
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css">
<style>
.swiper-container {
position: relative;
width: 100%;
padding-top: 20px;
height: 85px;
}
.swiper-slide {
position: relative;
text-align: center;
height: 22px;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.swiper-slide:after {
position: absolute;
display: block;
content: '';
width: 4px;
height: 22px;
right: 50%;
margin-right: -2px;
background: #FC552D;
}
.point{
position: absolute;
border-right: 6px solid transparent;
border-left: 6px solid transparent;
border-bottom: 12px solid #FC552D;
left: 50%; top: 47px;
margin-left: -6px;
}
.point:after {
position: absolute;
left: 50%; top: -40px;
margin-left: -3px;
display: block;
content: '';
width: 6px; height: 35px;
background: #FC552D;
}
.gradient {
display: block;
position: absolute;
top: 0;
z-index: 99;
width: 40%;
height: 85px;
}
.gradient.left {
left: 0;
background-image: -webkit-linear-gradient(right, rgba(255,255, 255, 0) 0, rgba(255,255, 255, 1) 100%);
}
.gradient.right {
right: 0;
background-image: -webkit-linear-gradient(left, rgba(255,255, 255, 0) 0, rgba(255,255, 255, 1) 100%);
}
</style>
</head>
<body>
<div class="swiper-container">
<div class="point"></div>
<div class="swiper-wrapper"></div>
<span class="gradient left"></span>
<span class="gradient right"></span>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/js/swiper.min.js"></script>
<script>
var mySwiper = new Swiper('.swiper-container', {
slidesPerView: 15, // 设置slider容器能够同时显示的slides数量
centeredSlides: true, // 设定为true时,active slide会居中,而不是默认状态下的居左
initialSlide: 99, // 设定初始化时slide的索引。
virtual: { // 开启虚拟Slide功能,可设置选项或设置为true则使用默认值,
slides: (function() { // 生成的刻度,100个
var slides = [];
for (var i = 0; i < 100; i += 1) {
slides.push('');
}
return slides;
}()),
},
on: {
slideChange() { // 你的事件
setTimeout(function() {
console.log(mySwiper.activeIndex); // mySwiper.activeIndex active slide的索引
});
},
}
});
</script>
</body>
</html>