Home > Web Front-end > JS Tutorial > How to use Zepto tap event penetration and point penetration (with code)

How to use Zepto tap event penetration and point penetration (with code)

php中世界最好的语言
Release: 2018-06-04 11:16:49
Original
2205 people have browsed it

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 ? &#39;Left&#39; : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? &#39;Up&#39; : null;<br/>                if (swipeDirectionFromVelocity) {<br/>                    touch.el.trigger(&#39;swipe&#39;)<br/>                    touch.el.trigger(&#39;swipe&#39;+ swipeDirectionFromVelocity)<br/>                }<br/>            })<br/>            .on(&#39;touchstart MSPointerDown pointerdown&#39;, function(e){<br/>                if((_isPointerType = isPointerEventType(e, &#39;down&#39;)) &&<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&#39;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 = $(&#39;tagName&#39; 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(&#39;touchmove MSPointerMove pointermove&#39;, function(e){<br/>                if((_isPointerType = isPointerEventType(e, &#39;move&#39;)) &&<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(&#39;touchend MSPointerUp pointerup&#39;, function(e){<br/>                if((_isPointerType = isPointerEventType(e, &#39;up&#39;)) &&<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>
Copy after login

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); })
Copy after login

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

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

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template