- 1.首先需要将滑块设置为绝对定位,脱离文档流,然后通过top来控制滑块的移动(当然用transform: translate()来控制更好,前提是得脱离文档流)
- 2.通过
@touchstart="gotouch(e)"来获取到点击的位置,再通过this.$refs.btn.$el.getBoundingClientRect().top,获取点击时元素离最上方的距离 - 3.再通过
@touchmove=touchM(e)来获取到滑动时元素在屏幕中的位置, - 4.最后在滑动的时候也就是触发
touchM事件的时候,将第一次点击元素获取到的元素位置,减去滑动时,元素的位置,在加上 获取到的元素离上方的距离即可
下面就是全部代码
<template>
<view>
<view ref="btn" class="box1" @touchstart="gotouch" @touchmove="touchM" :style="{top:topS+'px'}">
</view>
</view>
</template>
<script>
export default {
data() {
return {
first: 0,
topS: 0,
topAb: 0
}
},
methods: {
gotouch({
touches
}) {
this.topAb = this.$refs.btn.$el.getBoundingClientRect().top
this.first = touches[0].pageY
},
touchM({
touches
}) {
console.log(touches[0].pageY);
this.topS = touches[0].pageY - this.first + this.topAb
}
}
}
</script>
<style lang="scss" scoped>
.box1 {
width: 750rpx;
height: 500rpx;
background-color: aqua;
position: absolute;
left: 0;
top: 0;
}
</style>