介绍
基于 Vue.js 的滚动组件,实现避免触发 ios 浏览器的 bounce 效果
组件
<template>
<div class="scroll" ref="scroll">
<slot></slot>
</div>
</template>
<script>
export default {
name: "scroll",
data() {
return {};
},
mounted() {
this.scroll = this.$refs["scroll"];
this.scroll.addEventListener("touchstart", this.touchstartEvent);
this.scroll.addEventListener("touchmove", this.touchmoveEvent, {
passive: false
});
},
methods: {
getPoint(e) {
return {
x: e.touches ? e.touches[0].pageX : e.clientX,
y: e.touches ? e.touches[0].pageY : e.clientY
};
},
touchstartEvent(e) {
this.startPoint = this.getPoint(e);
},
touchmoveEvent(e) {
if (!this.startPoint) return;
const scrollTop = this.scroll.scrollTop;
const curPoint = this.getPoint(e);
const moveY = curPoint.y - this.startPoint.y;
if (moveY > 0) {
if (scrollTop <= 0) e.preventDefault();
} else {
const scrollHeight = this.scroll.scrollHeight;
const clientHeight = this.scroll.clientHeight;
const scrollBottom = scrollHeight - clientHeight - scrollTop;
if (scrollBottom <= 0) e.preventDefault();
}
}
}
};
</script>
<style scoped="scoped">
.scroll {
width: 100%;
height: 100%;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
</style>
调用
可在 app.vue 文件调用,全局使用
<template>
<scroll id="app">
<router-view />
</scroll>
</template>
<script>
import Scroll from "@/components/scroll";
export default {
components: {
Scroll
},
created() {}
};
</script>