Vue移动端滑动切换图片

实现的效果图

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

<template>
<div class="Banten">
<div class="Banten-top">腾讯课堂</div>
<div class="main">
<div id="slider" class="slider">
<img v-for="(src,index) in imgSrc" :key="index" :src="src"
@touchstart="touchstart"
@touchmove="touchmove"/>
</div>
<div class="title"><span class="number">{{showIndex+1}}<span class="littleNum">/{{this.imgSrc.length}}</span></span></div>
</div>
<Bottombar />
<Popuplayer />

</div>
</template>
<script>
export default {
name:'Multiple',
data() {
return {
startPointX: 0,
changePointX: 0,
showIndex: 0,
imgSrc:[
'http://img.juimg.com/tuku/yulantu/140216/330636-14021620411461.jpg',
'http://img1.imgtn.bdimg.com/it/u=53639861,996088844&fm=26&gp=0.jpg',
'http://04.imgmini.eastday.com/mobile/20180116/8c0d08e780d79721f63c0343632e1732.png'
]
}
},
methods:{
show(index){
this.changePointX=this.startPointX;
let slider = document.getElementById('slider');
slider.style.marginLeft=`-${330*index}px`;
},
touchstart(e){
this.startPointX = e.changedTouches[0].pageX;
},
touchmove(e){
if(this.startPointX==this.changePointX){
return ;
}
let currPointX = e.changedTouches[0].pageX;
let leftSlide = this.startPointX-currPointX;
if(leftSlide>30&&this.showIndex<this.imgSrc.length-1){
this.show(++this.showIndex)
}else if(leftSlide<-30&&this.showIndex>0){
this.show(--this.showIndex)
}
}
}
}
</script>
<style scoped>
.Banten{
background-color :rgb(10, 9, 9);
height: 100%;
position:fixed;
width: 100%;
}
.Banten-top{
height: 50px;
line-height: 50px;
color: #fff;
}
.main{
width: 100%;
}
.title{
width: 320px;
margin: 0 auto;
margin-top: 20px;
margin-bottom: 10px;
text-align: left;
font-size: 18px;
font-weight: 900;
}
.number{
float: right;
color: #fff;
}
.littleNum{
font-size: 12px;
font-weight: 300;
}
.slider{
overflow: hidden;
white-space: nowrap;
transition: 1s;
padding: 0 calc(50vw - 160px);
}
.slider img{
width: 330px;
display: inline;
margin-right: 10px;
}
</style>

说明:

v-for循环img标签,在每个img上监听touchstart和touchmove事件。

检测到touchstart事件后,使用startPointX记录一下touch时候的pageX值。

在滑动时touchmove事件是一直触发的。

当手指滑动的位置和touchstart时位置在x轴上的距离大于一个值时触发图片切换,我这里设置的是30px。

图片的切换我是通过改变margin-left实现的,代码里的330px是一个图片的宽度+图片直接的间距。具体业务里应该也是确定的,所以我就写死了。

作者:buppt
来源:CSDN
原文:https://blog.csdn.net/buppt/article/details/83662966