<template>
<div>
<div class="box">
<ul @touchstart='touchstart' @touchmove='touchmove' @touchend='touchend' class="scroll">
<li v-for="(item, i) in list" :key="i">列表{{i}}</li>
</ul>
</div>
</div>
</template>
<style>
.box{
height: 400px;
overflow: hidden;
border: 2px solid #cccccc;
width: 60px;
text-align: center;
position: fixed;
left: 10px;
top: 50%;
transform: translateY(-50%)
}
.box ul li{
display: flex;
flex-direction: column;
line-height: 30px;
}
</style>
<script>
// 參考:https://segmentfault.com/a/1190000017852497
export default {
data () {
return {
list: Array(16),
startY: 0,
maxDown: 40, //設置最大的下滑的區間
maxUpDown: 40, //設置最大的上滑底下留餘的區間
maxUpBounce: 0, //向上反彈
}
},
created () {
this.touch = {}
},
mounted () {
// 求一個上滑的最大的距離
let ulBox = document.getElementsByClassName('scroll')[0]
let box = document.getElementsByClassName('box')[0]
this.maxUp = - (ulBox.clientHeight - box.clientHeight + this.maxUpDown)
// 向下反彈值
this.maxDownBounce = - (ulBox.clientHeight - box.clientHeight)
},
methods: {
touchstart (e) {
this.touch.y1 = e.targetTouches[0].clientY
},
touchmove (e) {
this.scrollH = 0
this.touch.y2 = e.targetTouches[0].clientY
this.scrollH = this.startY + (this.touch.y2 - this.touch.y1)
// 限制最大的下滑空間
if(this.scrollH > this.maxDown) {
this.scrollH = this.maxDown
}
// 限制最大的上滑空間
if(this.scrollH < this.maxUp) {
this.scrollH = this.maxUp
}
scroll = document.getElementsByClassName('scroll')[0]
scroll.style.transform = `translateY(${this.scrollH}px)`
scroll.style.webkitTransform = `translateY(${this.scrollH}px)`
},
touchend (e) {
this.startY = this.scrollH
// 添加反彈的動畫
let ulBox = document.getElementsByClassName('scroll')[0]
if(this.startY > this.maxUpBounce) {
this.startY = this.maxUpBounce
ulBox.style.transition = 'transform .5s'
ulBox.style.transform = `translateY(${this.startY}px)`
ulBox.style.webkitTransform = `translateY(${this.startY}px)`
}
if(this.startY < this.maxDownBounce) {
this.startY = this.maxDownBounce
ulBox.style.transition = 'transform .5s'
ulBox.style.transform = `translateY(${this.startY}px)`
ulBox.style.webkitTransform = `translateY(${this.startY}px)`
}
}
}
}
</script>