介紹
vue-disbounce
是一款基于Vue.js
的自定義組件,可以有效避免觸發(fā)h5
頁(yè)面在ios
瀏覽器內(nèi)置的下拉bounce
效果唱矛。
組件
<template>
<div
:style="{'background-color':backgroundColor }"
class="vd-wrapper"
>
<div
class="vd"
ref="vd"
>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: "vd",
props: {
backgroundColor: {
type: String,
default: "#ffffff"
}
},
data() {
return {};
},
mounted() {
this.vd = this.$refs["vd"];
this.vd.addEventListener("touchstart", this.touchstartEvent);
this.vd.addEventListener("touchmove", this.touchmoveEvent, {
passive: false // 阻止默認(rèn)事件時(shí),設(shè)置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.vd.scrollTop; // 距離頁(yè)面頂部的距離
const curPoint = this.getPoint(e);
const moveY = curPoint.y - this.startPoint.y; // 縱向移動(dòng)的距離
// 下拉
if (moveY > 0) {
// 如果在頂部顷蟆,阻止瀏覽器默認(rèn)的滾動(dòng),避免觸發(fā)bounce
if (scrollTop <= 0) e.preventDefault();
// 上拉
} else {
const scrollHeight = this.vd.scrollHeight; // 全文區(qū)域的高度
const clientHeight = this.vd.clientHeight; // 可見(jiàn)區(qū)域的高度
const scrollBottom = scrollHeight - clientHeight - scrollTop; // 距離頁(yè)面底部的距離
// 如果在底部腐魂,阻止瀏覽器默認(rèn)的滾動(dòng)帐偎,避免觸發(fā)ios的bounce效果
if (scrollBottom <= 0) e.preventDefault();
}
}
}
};
</script>
<style scoped="scoped">
.vd-wrapper {
height: 100vh;
}
.vd {
width: 100%;
height: 100%;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
</style>
調(diào)用
為了方便調(diào)用,筆者已經(jīng)上傳到npm
npm安裝依賴npm i vue-disbounce
安裝完以后蛔屹,在app.vue
文件調(diào)用
<template>
<VueDisbounce id="app">
<!-- 如果有使用路由削樊, -->
<router-view />
</VueDisbounce>
</template>
<script>
import VueDisbounce from "vue-disbounce";
export default {
components: {
VueDisbounce
}
};
</script>
作者
SuperIron
相關(guān)鏈接
https://www.npmjs.com/package/vue-disbounce
https://github.com/SuperIron/vue-disbounce