search
HomeWeb Front-endJS TutorialHow to use Zepto tap event penetration and point penetration (with code)

This time I will show you how to use the Zepto tap event to penetrate and tap through (with code), and how to use the Zepto tap event to penetrate and tap through.What are the precautions, below This is a practical case, let’s take a look at it.

First of all, what is zepto tap event penetration?

Tap event penetration means that there are binding events on multiple levels. The top level is bound to the tap event, and the lower level is bound to the click event. After the upper level event is executed, Lower-level events will be triggered, and event penetration will occur. If the lower layer is input tag , it must penetrate.

The reason:

is because zepto implements the tap event to be triggered when it bubbles up to the document, that is, the tap event is It is bound to the document, and the click event has delayed execution.

Below we paste the source code of zepto.1.1.6 tap event:

<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 ? 'Down' : e.velocityY                 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                 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                         // 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>

Detailed analysis:

According to the zepto source code, we clearly know that the tap event is simulated by the touch event bound to the document. Therefore, when the user clicks on the tap event (touchstart, touchend), it needs to bubble up to the document before it is triggered. However, the user will trigger click events when touchstart and touchend, but at this time the click event is delayed for 300ms. If the tap event has been completed within this 300ms, the upper element will be deleted or hidden. When 300ms arrives, according to the principle of click events (when the element of the click event is at the top level, it will be in the click event, so sometimes the wrong z-index setting prevents the click event from being triggered), the lower-level event is executed and appears. penetration phenomenon. Let the lower layer be the input element. Even if no click event is bound, the penetration phenomenon is particularly serious due to its default focus on the pop-up keyboard.

Solution:

1. There is a fastclick plug-in on github to avoid the delayed execution of click events. After importing the file, add the following code and replace the tap event element that may cause penetration with click.

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

2. Listen for touchend events to replace tap, or touchstart, and prevent bubbling

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

3. Use css3 pointer-events : true and pointer-events : none are used interchangeably to set the underlying elements to prevent click events from being triggered.

4. Delay the disappearance of upper-layer elements so that the lower-layer click event cannot be triggered. Try to delay more than 350ms (I tested it on WeChat 6.3.15 on iOS9.2). However, this is a slightly bad experience. We can use CSS3 transition to improve the experience.

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

5. The ultimate solution: Replace all taps with click. Due to the delay of click, which causes experience problems, it is best to add the fastclick plug-in.

The following is a simple example I wrote: You can use your mobile phone to access http://property.pingan.com/app/test/jltest/tap-through.html?a= 1

Through the example, we can clearly see that the underlying button has the effect of being pressed after the event penetrates. During frequent testing, since WeChat caches the page and cannot see the immediately modified content, we can add some useless parameters to the URL such as a=1, so that the browser will reload.

<!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>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to access JS object properties and methods

How to use raw css3 to implement ring loading progress bar

The above is the detailed content of How to use Zepto tap event penetration and point penetration (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools