开发中使用antd ui 开发移动端页面
下拉框展开时 滑动下拉框内容 body 也会被拉动
- 猜测 原因是touchmove 事件穿透
- 处理方式: JS 禁止事件穿透
CSS 禁止BODY页面滚动
CSS 无法处理iOS微信端 情况 只能使用JS
组件获取焦点时设置 禁止滚动
const body = useRef(document.getElementsByTagName('body'));
// 聚焦时
const unScoll = () => {
if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
body.current[0].setAttribute('ontouchmove', 'event.preventDefault()');
} else {
body.current[0].style.overflowY = 'hidden';
}
};
// 失焦时
const scoll = () => {
if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
body.current[0].setAttribute('ontouchmove', '');
} else {
body.current[0].style.overflowY = 'scroll';
}
};
微信打开网页 不兼容ontouchmove='event.preventDefault()
// 判断是否微信打开
const isWechartView = () => {
const ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)?.toString() === "micromessenger") {
return true
} else {
return false
}
}
JS 处理方案
- 阻止默认事件
// 此事件必须提到组件外 不可简写在监听内部
const event = (e: any) => {
e.preventDefault();
}
// 禁止滑动调用
const unScoll = () => {
document.addEventListener('touchmove', event, { passive: false });
};
// 启动滑动
const scoll = () => {
document.removeEventListener('touchmove', event, false);
};