移动web app开发必备 - zepto事件问题
问题描述:
项目在祖先元素上绑定了 touchstart,touchmove,touchend事件,用来处理全局性的事件,比如滑动翻页
正常状态下:
- 用户在子元素上有交互动作时,默认状态下都是会冒泡到祖先元素响应
特定情况下:
- 子元素单独绑定了事件
- 特性情况下需要阻止全局事件
常规的做法就是stopPropagation阻止即可
但如果子元素绑定的是 click,touchmove,touchend这类事件的话,问题就来了
全局的touchstart事件也会被冒泡触发
发一段项目图:
/** * ppt事件接口 * * 允许用户自定义其行为 * 1 支持14种操作行为 * 2 默认对象都具有滑动翻页的特性 * 3 翻页的特性在遇到特性的情况可以被覆盖 * 比如 * 行为1:用户定义该名字可以支持 click 点击行为, 那么该元素左右滑动能过翻页 * 行为2:用户如果定义swipeLeft 行为,该元素左右滑动将不会翻页,因为默认翻页已经被覆盖 * * 此接口函数有作用域隔离 */ Xut.define('Xut.PPTevent', { //数据库预定义14个事件接口 defauleEventType: ['null', 'auto', 'tap', 'drag', 'dragTag', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'longTap', 'mTouchMagnify', 'mTouchNarrow', 'mTouchRotate' ], //绑定事件 bind: function(element, evtName, fn) { element.on(Xut.START_EV, function(e) { //阻止 mousedown事件冒泡 e.stopPropagation(); }); element.on(evtName, fn); //绑定真正事件 },
2 | on绑定的事件替换成硬编码容易理解 |
bind: function (element, evtName, fn) { element.on( 'mousedown' , function (e) { //阻止 mousedown事件冒泡 e.stopPropagation(); }); element.on( 'swipeLeft' , fn); //绑定真正事件 }, |
给元素绑定'swipeLeft'滑动事件,同时阻止'mousedown'冒泡到祖先元素,此时理论上就可行了
这样处理之后zepto移动事件确失效了
Zepto事件绑定
$(document.body) .bind('touchstart', function(e){ now = Date.now() delta = now - (touch.last || now) touch.el = $(parentIfText(e.touches[0].target)) touchTimeout && clearTimeout(touchTimeout) touch.x1 = e.touches[0].pageX touch.y1 = e.touches[0].pageY if (delta > 0 && delta <= 250) touch.isDoubleTap = true touch.last = now longTapTimeout = setTimeout(longTap, longTapDelay) }) .bind('touchmove', function(e){ cancelLongTap() touch.x2 = e.touches[0].pageX touch.y2 = e.touches[0].pageY if (Math.abs(touch.x1 - touch.x2) > 10) e.preventDefault() }) .bind('touchend', function(e){ cancelLongTap()
zepto移动事件失效的根源找到了,不能阻止事件冒泡了,不能拦截了
偏偏Zepto不让你这么安逸,学jquery的live()方法一样,把事件给绑到body元素上了, jquery1.7后就去掉了,zepto你也要跟上呀
处理的办法:
子元素上增加一个hack标记, 控制器冒泡过滤排除
onTouchStart: function (e) { var point = Xut.hasTouch ? e.touches[0] : e; if (!point) return; this.bindDefaultEventId = null; var children = point.target.offsetParent.children[0]; //处理默认特性 if (children.getAttribute('bindDefaultEvent')) { this.bindDefaultEventId = children.id; } else { var className = point.target.className; if (className && className === 'triggerAction') { //Actoin热点,通过冒泡捕获到 } else { if (className !== 'widgetwapper') { this.start = void 0; return; } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· [AI/GPT/综述] AI Agent的设计模式综述
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!