search
HomeWeb Front-endJS TutorialExamples of encapsulation of touch events in javascript mobile device web development_javascript skills

On touch screen devices, some basic gestures require secondary encapsulation of touch events.
zepto is a highly used class library on mobile terminals, but some events simulated by its touch module have some compatibility issues. For example, tap events have event penetration bugs on some Android devices, and other types There are also more or less compatibility issues in the events.

So, I simply encapsulated these commonly used gesture events myself. Since there are not many real devices to test, there may be some compatibility issues. The following code is only for iOS 7 and Andorid 4. The test passes in some common browsers.

tap event

The tap event is equivalent to the click effect in PC browsers. Although the click event is still available on touch screen devices, on many devices, there will be some delay in the click. If you want a quick response to the "click" event, you need This is achieved with the help of touch events.

Copy code The code is as follows:

var startTx, startTy;

element.addEventListener( 'touchstart', function( e ){
var touches = e.touches[0];

startTx = touches.clientX;
startTy = touches.clientY;
}, false );

element.addEventListener( 'touchend', function( e ){
var touches = e.changedTouches[0],
endTx = touches.clientX,
endTy = touches.clientY;

// On some devices, touch events are more sensitive, causing the event coordinates to change slightly when pressing and releasing your finger.
if( Math.abs(startTx - endTx) console.log( 'fire tap event' );
}
}, false );

doubleTap event

The doubleTap event is an event triggered when a finger taps the screen twice within the same position range and within a very short period of time. In some browsers, the doubleTap event will select text. If you do not want to select text, you can add the user-select:none css attribute to the element.

Copy code The code is as follows:

var isTouchEnd = false,
lastTime = 0,
lastTx = null,
lastTy = null,
firstTouchEnd = true,
body = document.body,
dTapTimer, startTx, startTy, startTime;

element.addEventListener( 'touchstart', function( e ){
if( dTapTimer ){
clearTimeout( dTapTimer );
dTapTimer = null;
}

var touches = e.touches[0];

startTx = touches.clientX;
startTy = touches.clientY;
}, false );

element.addEventListener( 'touchend', function( e ){
var touches = e.changedTouches[0],
endTx = touches.clientX,
endTy = touches.clientY,
now = Date.now(),
duration = now - lastTime;

// First make sure that a single tap event can be triggered
if( Math.abs(startTx - endTx) // The interval between two taps must be within 500 milliseconds
if( duration // A certain range of error is allowed between this tap position and the previous tap position
if( lastTx !== null &&
Math.abs(lastTx - endTx) Math.abs(lastTy - endTy)

firstTouchEnd = true;
lastTx = lastTy = null;
console.log( 'fire double tap event' );
}
}
else{
lastTx = endTx ;
lastTy = endTy;
}
}
else{
firstTouchEnd = true;
lastTx = lastTy = null;
}

lastTime = now;
}, false );

// On iOS Safari, if your finger taps the screen too fast,
// there is a certain chance that the touchstart and touchend events will not respond the second time
// At the same time, the finger taps for a long time touch does not trigger click

if( ~navigator.userAgent.toLowerCase().indexOf('iphone os') ){

body.addEventListener( 'touchstart', function( e ){
startTime = Date.now();
}, true );

body.addEventListener( 'touchend', function( e ){
var noLongTap = Date.now() - startTime

if( firstTouchEnd ){
firstTouchEnd = false;
if( noLongTap && e.target === element ){
dTapTimer = setTimeout(function(){
         firstTouchEnd = true;
           lastTx = lastTy = null; }
else{
firstTouchEnd = true ;
}
}, true );

// On iOS, the click event will not be triggered when the finger taps the screen multiple times too fast
element.addEventListener( 'click', function( e ){
if( dTapTimer ){

clearTimeout( dTapTimer );

dTapTimer = null;
firstTouchEnd = true;
}
}, false );

}

longTap event

The longTap event is an event triggered when a finger presses the screen for a long time without moving.

Copy code

The code is as follows:

var startTx, startTy, lTapTimer;

element.addEventListener( 'touchstart', function( e ){
  if( lTapTimer ){
    clearTimeout( lTapTimer );
    lTapTimer = null;
  }

  var touches = e.touches[0];

  startTx = touches.clientX;
  startTy = touches.clientY;

  lTapTimer = setTimeout(function(){
    console.log( 'fire long tap event' );
  }, 1000 );

  e.preventDefault();
}, false );

element.addEventListener( 'touchmove', function( e ){
  var touches = e.touches[0],
    endTx = touches.clientX,
    endTy = touches.clientY;

  if( lTapTimer && (Math.abs(endTx - startTx) > 5 || Math.abs(endTy - startTy) > 5) ){
    clearTimeout( lTapTimer );
    lTapTimer = null;
  }
}, false );

element.addEventListener( 'touchend', function( e ){
  if( lTapTimer ){
    clearTimeout( lTapTimer );
    lTapTimer = null;
  }
}, false );

swipe事件

swipe 事件是当手指在屏幕上滑动后触发的事件,根据手指滑动的方向又分为 swipeLeft (向左)、swipeRight (向右)、swipeUp (向上)、swipeDown (向下)。

复制代码 代码如下:

var isTouchMove, startTx, startTy;

element.addEventListener( 'touchstart', function( e ){
  var touches = e.touches[0];

  startTx = touches.clientX;
  startTy = touches.clientY;
  isTouchMove = false;
}, false );

element.addEventListener( 'touchmove', function( e ){
  isTouchMove = true;
  e.preventDefault();
}, false );

element.addEventListener( 'touchend', function( e ){
  if( !isTouchMove ){
    return;
  }

  var touches = e.changedTouches[0],
    endTx = touches.clientX,
    endTy = touches.clientY,
    distanceX = startTx - endTx
    distanceY = startTy - endTy,
    isSwipe = false;

  if( Math.abs(distanceX) >= Math.abs(distanceY) ){
    if( distanceX > 20 ){
      console.log( 'fire swipe left event' );
      isSwipe = true;
    }
    else if( distanceX       console.log( 'fire swipe right event' );   
      isSwipe = true;
    }
  }
  else{
    if( distanceY > 20 ){
      console.log( 'fire swipe up event' );       
      isSwipe = true;
    }
    else if( distanceY       console.log( 'fire swipe down event' );        
      isSwipe = true;
    }
  }

  if( isSwipe ){
    console.log( 'fire swipe event' );
  }
}, false );

上面模拟的事件都封装在 MonoEvent 中了。完整代码地址:https://github.com/chenmnkken/monoevent,需要的朋友看看吧~

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),