Vue.js 实现禁止 ios 浏览器的 bounce 效果

1 篇文章 0 订阅
1 篇文章 0 订阅

介绍

基于 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 // 阻止默认事件时,设置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) {
					// 如果在顶部,阻止浏览器默认的滚动,避免触发bounce
					if (scrollTop <= 0) e.preventDefault();

					// 上拉
				} else {
					const scrollHeight = this.scroll.scrollHeight; // 全文区域的高度
					const clientHeight = this.scroll.clientHeight; // 可见区域的高度
					const scrollBottom = scrollHeight - clientHeight - scrollTop; // 距离页面底部的距离

					// 如果在底部,阻止浏览器默认的滚动,避免触发ios的bounce效果
					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>
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值