1、封装为组件,方便调用
<template lang="pug">
.scroll-lock-container(@touchstart="onTouchStart" @touchmove="onTouchMove")
slot
</template>
<script>
export default {
name: "scrollLock",
props: {
scrollEl: String
},
data() {
return {
target: null,
pageY: 0,
preventDefault: false,
ignoreMove: false
}
},
methods: {
onTouchStart(e) {
this.pageY = e.touches[0].pageY
let targets = this.scrollEl ? this.$el.querySelectorAll(this.scrollEl) : [this.$el]
let path = e.path || (e.composedPath && e.composedPath());
//子scroll-lock触发则忽略
this.ignoreMove = false;
for (let i = 0; i < path.length; i++) {
if (this.$el == path[i]) {
break;
}
if(path[i].classList.contains(‘scroll-lock-container‘)) {
this.ignoreMove = true
break;
}
}
//如果不在滚动区域触发则禁止
this.target = null;
if (this.scrollEl && !this.ignoreMove) {
this.preventDefault = true;
for (let i = 0; i < path.length; i++) {
for (let j = 0; j < targets.length; j++) {
if (targets[j] == path[i]) {
this.target = targets[j];
this.preventDefault = false;
break;
}
}
if(this.target) {
break;
}
}
}
},
onTouchMove(e) {
if (this.ignoreMove) {
return;
}
//不是滚动区域的固定忽略
if (this.preventDefault) {
e.preventDefault()
return
}
const distanceY = e.touches[0].pageY - this.pageY
if (distanceY > 0 && this.target.scrollTop <= 0) {
e.preventDefault()
} else if (distanceY < 0 && this.target.scrollTop >= (this.target.scrollHeight - this.target.clientHeight)) {
e.preventDefault()
}
},
}
}
</script>
2、内容引用
页面调用:
scroll-lock(:scrollEl="‘.listConHeight ul‘").listBox
.personTab(v-if="isPerson") 个人排行榜
.comPanyTab(v-else)
import ScrollLock from ‘../components/scrollLock‘;
components:{
ScrollLock
},
移动端滑动下滑时抖动处理