最近公司功能需求要把新开发的h5页面嵌入ios端app中,遇到这个让人很是头疼的一个问题,h5页面在ios端,页面一直存在回弹效果。如果直接对body禁止的话,然后个页面都无法滑动了。今天终于搞定了这个问题,特此记录下
由于公司要求用vue3.0开发,所以在此就直接用3.0来记录了。
一 首先我们要在 setup()中定义两个方法
注意 :此处的方法需要return出去,方可使用
setup(){
// 滑动开始获取初始位置坐标
function touchstartFunction(e) {
this.startY = e.touches[0].pageY;
}
// 监听手指滑动事件
function touchmoveFunction(e) {
let el = document.querySelector(".sidebar"); // 需要滑动的dom元素这个为包裹滑动元素的父元素
if (!e.isSCROLL) {
e.preventDefault(); // 阻止默认事件(上下滑动)
console.log("阻止了");
} else {
// 需要滑动的区域
let moveY = e.touches[0].pageY;
let top = el.scrollTop;
let ch = el.clientHeight; // 对象最顶端和窗口最顶端之间的距离
let scrollH = el.scrollHeight; // 含滚动内容的元素大小
if (
(top === 0 && moveY > this.startY) ||
(top + ch === scrollH && moveY < this.startY)
) {
e.preventDefault();
console.log("阻止了");
} else {
console.log("开启了");
}
}
}
return {
touchstartFunction,
touchmoveFunction,
}
注意 :vue3.0的生命周期的调用需要我们先导入
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
二 然后在onMounted生命周期函数中添加事件监听
onMounted(() => {
// 禁止ios橡皮筋效果(弹簧效果)
// ********************
let ios = navigator.userAgent.indexOf("iphone"); // 判断是否为ios
// 获取触摸坐标
document.body.addEventListener("touchstart", touchstartFunction, {
passive: false,
});
//
if (ios === -1) {
// ios下运行
let el = document.querySelector(".sidebar"); // 需要滑动的dom元素
iosTrouchFn(el);
}
function iosTrouchFn(el) {
// el需要滑动的元素
el.addEventListener("touchmove", function (e) {
e.isSCROLL = true;
});
document.body.addEventListener("touchmove", touchmoveFunction, {
passive: false,
}); // passive防止阻止默认事件不生效
}
});
三 然后在onBeforeUnmount生命周期函数中移除事件监听
onBeforeUnmount(() => {
document.body.removeEventListener("touchstart", touchstartFunction, {
passive: false,
});
document.body.removeEventListener("touchmove", touchmoveFunction, {
passive: false,
});
});