需求背景:
原生应用嵌套h5页面,需要前端做一个自定义的长按事件,原生js封装touch事件,代码如下 :
let timer = 0;
const touchStart = function (event, callback, data = {}) {
// const eve = window.event || event;
// eve.preventDefault ? eve.preventDefault() : (eve.returnValue = false);
timer = setTimeout(() => {
callback(event, data);
}, 500);
return false;
};
const touchEnd = function () {
clearTimeout(timer);
return false;
};
const touchMove = function () {
// 使用ontouchmove调用 移动即清除
clearTimeout(timer);
timer = 0;
};
export { touchStart, touchMove, touchEnd };
此代码中,以下两行代码可以在其他手机浏览器中正常唤起自定义的菜单,唯独华为手机不行,不限制机型,因为本人目前没有华为手机,尚不明白鸿蒙系统webview的机制,希望有知道的大佬帮忙解惑,十分感谢。
另外这个阻止默认事件会有导致其他的问题,会当前页面滑动失效,经过多处查阅资料,发现可以通过css来解决,代码如下
* {
-webkit-touch-callout: none !important;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
可以通过touch-callout 与user-select搭配实现禁用默认长按菜单的效果,可满足大部分场景需求 ,这个可以解决华为手机自定义长按事件失效的问题。