HTML:
<template>
<view class="swiper">
<view class="swiper-item" :style="{
left:leftMove+'px'
}">
<image class="img" v-for="item,index in list" :key="index" :src="item" mode=""></image>
</view>
</view>
</template>
CSS:
.swiper {
overflow: hidden;
width: 100%;
height: 300rpx;
position: relative;
.swiper-item {
display: inline-block;
white-space: nowrap;
height: 100%;
position: absolute;
top: 0;
.img {
width: 600rpx;
height: 300rpx;
flex-shrink: 0;
}
}
}
JS:
mounted() {
//获取swiper总宽度
let query = uni.createSelectorQuery().in(this);
query.select('.swiper').boundingClientRect(data => {
this.boxWidth = data.width
}).exec();
//获取item宽度
query.selectAll('.img').boundingClientRect(data => {
this.itemWidth = data[0].width
}).exec();
//获取swiper盒子宽度
query.select('.swiper-item').boundingClientRect(data => {
this.allWidth = data.width
this.scrollSwiper()
}).exec();
},
data() {
return {
allWidth: 0,//swiper盒子宽度
leftMove: 0,//左移距离
boxWidth: 0,//大盒子宽度
itemWidth:0,//item宽度
timer: null,//定时器
list: [],//图片列表
}
},
methods: {
scrollSwiper() {
let query = uni.createSelectorQuery().in(this);
let num = 0
let speed = 0.1
//计算停止的位置
let stopWitdh = (this.allWidth - this.boxWidth) - (this.itemWidth * 2)
let midNum = stopWitdh / 2
//运动速度
this.timer = setInterval(() => {
num++
if (num % 10 == 0) {
if (Math.abs(this.leftMove) <= midNum) {
speed += 0.2
} else {
speed <= 0.2 ? speed = 0.8 : speed -= 0.2
}
}
this.leftMove = this.leftMove - speed
if (Math.abs(this.leftMove) >= stopWitdh) clearInterval(this.timer)
}, 0)
},
}