讲师中心 微信公众号
AI工具推荐 视频效率加速

如何使用Zepto tap事件的穿透与点透(附代码)

酷伟酱_8660

酷伟酱_8660

发布时间:2018-06-04 11:16:49

|

2413人浏览过

|

来源于php中文网

原创

这次给大家带来如何使用Zepto tap事件的穿透与点透(附代码),使用Zepto tap事件的穿透与点透注意事项有哪些,下面就是实战案例,一起来看一下。

首先,什么是zepto tap事件穿透?

tap事件穿透就是,有多个层级上有绑定事件,最上层的绑定了tap事件,下层绑定了click事件,在执行完上层事件后会触发下层事件,进而出现事件穿透。如果下层是input标签,必穿透。

究其原因:

是因为zepto实现tap事件是冒泡到document上时才触发的,也就是tap事件是绑定在document上,而click事件有延时执行。

下面我们贴下zepto.1.1.6 tap事件的源码:

<span style="font-size: 14px;">;(function($){<br/>    var touch = {},<br/>        touchTimeout, tapTimeout, swipeTimeout, longTapTimeout,<br/>        longTapDelay = 750,<br/>        gesture<br/>    function swipeDirection(x1, x2, y1, y2) {<br/>        return Math.abs(x1 - x2) >=<br/>            Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')<br/>    }<br/>    function longTap() {<br/>        longTapTimeout = null<br/>        if (touch.last) {<br/>            touch.el.trigger('longTap')<br/>            touch = {}<br/>        }<br/>    }<br/>    function cancelLongTap() {<br/>        if (longTapTimeout) clearTimeout(longTapTimeout)<br/>        longTapTimeout = null<br/>    }<br/>    function cancelAll() {<br/>        if (touchTimeout) clearTimeout(touchTimeout)<br/>        if (tapTimeout) clearTimeout(tapTimeout)<br/>        if (swipeTimeout) clearTimeout(swipeTimeout)<br/>        if (longTapTimeout) clearTimeout(longTapTimeout)<br/>        touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null<br/>        touch = {}<br/>    }<br/>    function isPrimaryTouch(event){<br/>        return (event.pointerType == 'touch' ||<br/>            event.pointerType == event.MSPOINTER_TYPE_TOUCH)<br/>            && event.isPrimary<br/>    }<br/>    function isPointerEventType(e, type){<br/>        return (e.type == 'pointer'+type ||<br/>            e.type.toLowerCase() == 'mspointer'+type)<br/>    }<br/>    $(document).ready(function(){<br/>        var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType<br/>        if ('MSGesture' in window) {<br/>            gesture = new MSGesture()<br/>            gesture.target = document.body<br/>        }<br/>        $(document)<br/>            .bind('MSGestureEnd', function(e){<br/>                var swipeDirectionFromVelocity =<br/>                        e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null;<br/>                if (swipeDirectionFromVelocity) {<br/>                    touch.el.trigger('swipe')<br/>                    touch.el.trigger('swipe'+ swipeDirectionFromVelocity)<br/>                }<br/>            })<br/>            .on('touchstart MSPointerDown pointerdown', function(e){<br/>                if((_isPointerType = isPointerEventType(e, 'down')) &&<br/>                    !isPrimaryTouch(e)) return<br/>                firstTouch = _isPointerType ? e : e.touches[0]<br/>                if (e.touches && e.touches.length === 1 && touch.x2) {<br/>                    // Clear out touch movement data if we have it sticking around<br/>                    // This can occur if touchcancel doesn't fire due to preventDefault, etc.<br/>                    touch.x2 = undefined<br/>                    touch.y2 = undefined<br/>                }<br/>                now = Date.now()<br/>                delta = now - (touch.last || now)<br/>                touch.el = $('tagName' in firstTouch.target ?<br/>                    firstTouch.target : firstTouch.target.parentNode)<br/>                touchTimeout && clearTimeout(touchTimeout)<br/>                touch.x1 = firstTouch.pageX<br/>                touch.y1 = firstTouch.pageY<br/>                if (delta > 0 && delta <= 250) touch.isDoubleTap = true<br/>                touch.last = now<br/>                longTapTimeout = setTimeout(longTap, longTapDelay)<br/>                // adds the current touch contact for IE gesture recognition<br/>                if (gesture && _isPointerType) gesture.addPointer(e.pointerId);<br/>            })<br/>            .on('touchmove MSPointerMove pointermove', function(e){<br/>                if((_isPointerType = isPointerEventType(e, 'move')) &&<br/>                    !isPrimaryTouch(e)) return<br/>                firstTouch = _isPointerType ? e : e.touches[0]<br/>                cancelLongTap()<br/>                touch.x2 = firstTouch.pageX<br/>                touch.y2 = firstTouch.pageY<br/>                deltaX += Math.abs(touch.x1 - touch.x2)<br/>                deltaY += Math.abs(touch.y1 - touch.y2)<br/>            })<br/>            .on('touchend MSPointerUp pointerup', function(e){<br/>                if((_isPointerType = isPointerEventType(e, 'up')) &&<br/>                    !isPrimaryTouch(e)) return<br/>                cancelLongTap()<br/>                // swipe<br/>                if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) ||<br/>                    (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30))<br/>                    swipeTimeout = setTimeout(function() {<br/>                        touch.el.trigger('swipe')<br/>                        touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2)))<br/>                        touch = {}<br/>                    }, 0)<br/>                // normal tap<br/>                else if ('last' in touch)<br/>                // don't fire tap when delta position changed by more than 30 pixels,<br/>                // for instance when moving to a point and back to origin<br/>                    if (deltaX < 30 && deltaY < 30) {<br/>                        // delay by one tick so we can cancel the 'tap' event if 'scroll' fires<br/>                        // ('tap' fires before 'scroll')<br/>                        tapTimeout = setTimeout(function() {<br/>                            // trigger universal 'tap' with the option to cancelTouch()<br/>                            // (cancelTouch cancels processing of single vs double taps for faster 'tap' response)<br/>                            var event = $.Event('tap')<br/>                            event.cancelTouch = cancelAll<br/>                            touch.el.trigger(event)<br/>                            // trigger double tap immediately<br/>                            if (touch.isDoubleTap) {<br/>                                if (touch.el) touch.el.trigger('doubleTap')<br/>                                touch = {}<br/>                            }<br/>                            // trigger single tap after 250ms of inactivity<br/>                            else {<br/>                                touchTimeout = setTimeout(function(){<br/>                                    touchTimeout = null<br/>                                    if (touch.el) touch.el.trigger('singleTap')<br/>                                    touch = {}<br/>                                }, 250)<br/>                            }<br/>                        }, 0)<br/>                    } else {<br/>                        touch = {}<br/>                    }<br/>                deltaX = deltaY = 0<br/>            })<br/>            // when the browser window loses focus,<br/>            // for example when a modal dialog is shown,<br/>            // cancel all ongoing events<br/>            .on('touchcancel MSPointerCancel pointercancel', cancelAll)<br/>        // scrolling the window indicates intention of the user<br/>        // to scroll, not tap or swipe, so cancel all ongoing events<br/>        $(window).on('scroll', cancelAll)<br/>    })<br/>    ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown',<br/>        'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){<br/>            $.fn[eventName] = function(callback){ return this.on(eventName, callback) }<br/>        })<br/>})(Zepto)</span>

详细分析:

根据zepto源码,我们很清楚地知道tap事件是通过绑定在document上的touch事件来模拟的。所以用户在点击tap事件(touchstart、touchend)时需要冒泡到document上才会触发。然而用户在touchstart和touchend时会触发click事件,但是此时click事件处于延时300ms,如果在这300ms之内tap事件已经完成,将上层元素删除或隐藏。在300ms到来之际,根据click事件的原则(当click事件的元素处于最上层时会处于click事件,所以有的时候错误的z-index的设置导致无法触发click事件),下层事件被执行,出现穿透现象。让下层是input元素,即使没有绑定click事件,由于其默认聚焦弹出键盘,穿透现象尤为严重。

解决方案:

1、github上有个fastclick插件,用来规避click事件的延时执行。引入文件后添加如下代码,并用click替代可能会导致穿透的tap事件元素。

$(function(){ new FastClick(document.body); })

2、监听touchend事件来替代tap,或者touchstart,并阻止冒泡

$("#close").on("touchend",function(e){
$("#alertBox").hide();
e.preventDefault();
});

3、使用css3的pointer-events : true   和 pointer-events : none交替使用对下层元素设置,阻止触发click事件。

4、延时消失上层元素,使得无法触发下层click事件,尽量在延时350ms以上(本人在ios9.2上微信6.3.15上测试过)。不过这样稍微有些体验不好,我们可以使用css3过度来改善体验。

setTimeout(function(){ $(#alertBox).hide(); } , 350 );

5、终极方案:用click替代所有tap。由于click的延时,导致体验问题,最好加上fastclick插件。

下面是我写了个简单的例子:可以用手机访问http://property.pingan.com/app/test/jltest/tap-through.html?a=1

通过例子,我们可以很明显的看到事件穿透后底层的button有按下的效果。在频繁的测试过程中,由于微信会缓存页面导致无法看到即时修改的内容,我们可以通过给url增加一些没用的参数如a=1,这样浏览器就会重新加载。

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
 <title>test-tap-through</title>
 <script src="js/zepto.min.js" charset="utf-8"></script>
 <style media="screen">
 body{
 margin: 0;
 padding: 0;
 }
 .test1,.test2{
 position: relative;
 }
 .button{
 width: 90%;
 height: 75px;
 background-color: #00ffff;
 margin: 5%;
 line-height: 75px;
 text-align: center;
 font-size: 40px;
 }
 .box{
 position: absolute;
 top:0;
 left: 0;
 width: 50%;
 height: 200px;
 background-color: #ff00ff;
 margin: 5%;
 line-height: 100px;
 text-align: center;
 font-size: 40px;
 z-index: 100;
 }
 </style>
</head>
<body>
 <p>
 <input type="button" id="button1" value="button1">
 <input type="button" id="button2" value="button2">
 <p id="box1" style="display:none">box1</p>
 <p id="box2" style="display:none">box2</p>
 </p>
 <p>
 <input type="button" id="button3" value="button3">
 <input type="button" id="button4" value="button4">
 <p id="box3" style="display:none">box3</p>
 <p id="box4" style="display:none">box4</p>
 </p>
</body>
<script type="text/javascript">
 $("#button1").click(function(){
 $("#box2").hide();
 $("#box1").show();
 });
 $("#button2").click(function(){
 $("#box1").hide();
 $("#box2").show();
 });
 $("#box2").tap(function(){
 $("#box2").hide();
 });
 $("#box1").tap(function(){
 $("#box1").hide();
 });
 $("#button3").click(function(){
 $("#box4").hide();
 $("#box3").show();
 });
 $("#button4").click(function(){
 $("#box3").hide();
 $("#box4").show();
 });
 $("#box3").tap(function(){
 setTimeout(function(){$("#box3").hide();},350);
 
 });
 $("#box4").tap(function(){
 setTimeout(function(){$("#box4").hide();},350);
 
 });
</script>
</html>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何访问JS的对象属性与方法

3D传送带视差照片预览特效
3D传送带视差照片预览特效

gsap zepto制作酷炫大气的3D传送带图片布局,点击鼠标拖拽视差图片预览特效。

下载

如何使用源生css3实现圆环加载进度条

热门AI工具

更多
咔片AIPPT

一款在线AI演示文稿制作工具,可根据主题和内容需求辅助生成PPT结构与页面,提高演示材料制作效率。

SkildArt
SkildArt Hot

SkildArt是一款AI文本写作工具,一站式 AI 视觉创作平台。

DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

Atoms
Atoms Hot

Atoms是一款AI智能体工具,第一支自动构建真实业务的 AI 团队。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

讯飞绘文

讯飞绘文是一款由科大讯飞推出的一站式 AIGC 内容运营平台。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

相关专题

更多
PixTV官网入口地址合集
PixTV官网入口地址合集

本专题汇总了 PixTV AI 一站式视频创作平台的官方入口与使用教程。无需下载软件,浏览器直接访问即可使用。平台将剧本、图像、视频、声音与剪辑整合在“无限画布”中,接入 GPT Image 2.5、Seedance 2.5 等头部模型。本专题整理了从新建画布、角色锚定、分镜拆分到视频生成与导出的完整操作指南,助你快速上手 AI 短剧与漫剧创作。

80

2026.10.10

Kratos框架HTTP与gRPC服务开发教程
Kratos框架HTTP与gRPC服务开发教程

本专题围绕Kratos框架双协议服务开发,涵盖HTTP路由与处理器编写、参数获取、gRPC服务实现与客户端调用、metadata上下文传递、encoding编解码注册、统一响应封装、超时控制与流式响应实现方法。

40

2026.10.10

Kratos框架Protobuf接口定义与代码生成合集
Kratos框架Protobuf接口定义与代码生成合集

本专题讲解Kratos框架接口定义体系,涵盖proto编写规范、proto add/client/server生成命令、http注解路由、validate校验、OpenAPI文档生成、跨服务proto复用与兼容性设计。

20

2026.10.10

C++虚函数怎么定义和调用
C++虚函数怎么定义和调用

C++虚函数是实现运行时多态的重要机制。本专题从virtual关键字的基本用法入手,介绍基类与派生类之间的函数重写、基类指针调用派生类方法,以及动态绑定的执行过程,帮助初学者掌握虚函数的核心语法。

40

2026.10.10

C++类与对象的封装方法教程
C++类与对象的封装方法教程

C++封装是面向对象编程的核心特性之一,通过类将数据与操作数据的函数组织在一起,并利用访问权限控制外部访问。本专题介绍类的定义、成员变量、成员函数以及public、private和protected的使用方法,帮助初学者掌握封装的基本原理。

20

2026.10.10

C++构造函数定义与调用方法
C++构造函数定义与调用方法

C++构造函数用于初始化类对象,是面向对象编程的重要基础。本专题从构造函数的定义、声明和调用入手,介绍默认构造函数、带参数构造函数、拷贝构造函数及成员初始化列表,帮助初学者掌握对象创建与初始化的基本方法。

40

2026.10.10

Kratos框架零基础入门教程
Kratos框架零基础入门教程

本专题整理Kratos框架入门内容,涵盖Go环境准备、kratos CLI安装升级、new命令创建项目、目录结构分层说明、服务启动与双协议端口、依赖下载报错排查,帮助开发者快速跑通第一个Kratos框架微服务应用。

20

2026.10.10

C++条件判断语句怎么写
C++条件判断语句怎么写

C++条件判断是控制程序执行流程的重要基础。本专题介绍if、if-else、else if和switch等常见分支语句,结合条件表达式、比较运算符与代码示例,帮助初学者掌握不同场景下的判断逻辑。

20

2026.10.10

C++变量怎么声明和赋值
C++变量怎么声明和赋值

C++变量是编写程序和存储数据的基础。本专题围绕变量声明、定义、初始化、赋值和类型选择等内容展开,帮助初学者理解不同变量的用法,并掌握在实际代码中定义和使用变量的方法。

20

2026.10.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn