search
HomeWeb Front-endJS TutorialDetailed introduction to the basics of JavaScript mobile events and a summary of commonly used event libraries

This article mainly introduces the basics of js mobile events and common event libraries in detail. It has certain reference value. Interested friends can refer to it

1. Event Basics

PC: click, mouseover, mouseout, mouseenter, mouseleave, mousemove, mousedown, mouseup, mousewheel, keydown, keyup, load, scroll, blur, focus, change...

Mobile terminal: click (click), load, scroll, blur, focus, change, input (replacing keyup, keydown)...TOUCH event model (processing single-finger operations), GESTURE event model (processing multi-finger operations)

TOUCH: touchstart, touchmove, touchend, touchcancel

GESTURE: gesturestart, gesturechange, gestureend

1. Click: On the mobile side, click is a click event, not a click event. In mobile projects, we often distinguish between what a click does and what a double-click does. Therefore, when the mobile browser recognizes a click, it will only execute it after confirming that it is a click:

On the mobile side There will be a 300ms delay when using click: after the first click is completed, the browser needs to wait 300ms to see whether the second click is triggered. If the second click is triggered, it is not a click, and the second click is not triggered. It belongs to click

The following code is the code to simulate the click time on the mobile side


function on(curEle,type,fn){
   curEle.addEventListener(type,fn,false);
  }
  var oBox = document.querySelector('.box');
  //移动端采用click存在300ms延迟
  // oBox.addEventListener('click',function(){
  //  this.style.webkitTransform = 'rotate(360deg)'
  // },false)
  //使用TOUCH事件模型实现点击操作(单击&&双击)
  on(oBox,'touchstart',function(ev){
   //ev:TouchEvent事件 属性 type、target、preventDefault(returnValue)、stopPropagation、changedTouches、touches
   //changedTouches和touches都是手指信息的集合(touchList),touches获取到值的必要条件只有手指还在屏幕上才可以获取,所以在touchend事件中如果想获取手指离开的瞬间坐标只能使用changedTouches获取
   var point = ev.touches[0];
   this['strX'] = point.clientX;
   this['strY'] = point.clientY;
   this['isMove'] = false;
  })
  on(oBox,'touchmove',function(ev){
   var point = ev.touches[0];
   var newX = point.clientX,
    newY = point.clientY;
   //判断是否发生滑动,我们需要判断偏移的值是否在30PX以内
   if(Math.abs(newX-this['strX'])>30 || Math.abs(newY-this['strY'])>30){
    this['isMove'] = true;
   }
  })
  on(oBox,'touchend',function(ev){
   if(this['isMove'] === false){
    //没有发生移动 点击
    this.style.webkitTransitionDuration = '1s';
    this.style.webkitTransform = 'rotate(360deg)';
    var delayTimer = window.setTimeout(function(){
     this.style.webkitTransitionDuration = '0s';
     this.style.webkitTransform = 'rotate(0deg)';
    }.bind(this),1000);
   }else{
    //滑动
    this.style.background = 'red';
   }
  })

At the same time, fastclick.js can also be used to solve the 300ms of the click event on the mobile side. Delay (github address https://github.com/zhouxiaotian/fastclick)

2. Click, click, double-click, long press, slide, slide left, slide right, slide up, slide down

Click and double-click (300MS)

Click and long press (750MS)

Click and slide (whether the X/Y axis offset distance is within 30PX, if it exceeds 30PX, it is sliding)

Swipe left and right and slide up and down (X-axis offset distance > Y-axis offset distance = Left and right slides, the opposite is up and down)

Left slide and right slide (Offset distance >0 = Swipe right (the opposite is swipe left)

2. Commonly used event libraries

FastClick.js: Solve the 300MS delay of CLICK event

TOUCH.js: Baidu Cloud Mobile Gesture Library GitHub address https://github.com/Clouda-team/touch.code.baidu.com

The examples are as follows:


var oBox = document.querySelector('.box');
  //单击
  touch.on(oBox,'tap',function(ev){
   this.style.webkitTransitionDuration = '1s';
   this.style.webkitTransform = 'rotate(360deg)';
   var delayTimer = window.setTimeout(function(){
    this.style.webkitTransitionDuration = '0s';
    this.style.webkitTransform = 'rotate(0deg)';
    window.clearTimeout(delayTimer)
   }.bind(this),1000)
  })
  //双击
  touch.on(oBox,'doubletap',function(ev){
   this.style.webkitTransitionDuration = '1s';
   this.style.webkitTransform = 'rotate(-360deg)';
   var delayTimer = window.setTimeout(function(){
    this.style.webkitTransitionDuration = '0s';
    this.style.webkitTransform = 'rotate(0deg)';
    window.clearTimeout(delayTimer)
   }.bind(this),1000)
  })
  //长按
  touch.on(oBox,'hold',function(ev){
   this.style.backgroundColor = 'red';
  })

HAMMER.js

Zepto.js: Known as the small JQ on the mobile side, JQ is used on the PC side, so the code contains a lot of compatibility with low-version IE browsers Processing, and ZEPTO is only used in mobile development, so there is no support for lower versions of IE on the basis of JQ

JQ provides a lot of selector types and DOM operation methods, but ZEPTO only implements Some commonly used selectors and methods. For example: the animation methods in JQ include animate, hide, show, fadeIn, fadeOut, fadeToggle, slideDown, slideUp, slideToggle... but in ZEPTO there is only animate

The source code size of ZEPTO is much smaller than that of JQ

ZEPTO was specially developed for mobile terminals, so it is more suitable for mobile terminals than JQ:

ZEPTO’s animate animation method supports the operation of CSS3 animations

ZEPTO is specialized for mobile terminals We have prepared commonly used event operations on mobile terminals: tap, singleTap, doubleTap, longTap, swipe, swipeUp, swipeDown, swipeLeft, swipeRight

The example code is as follows:


$('.box').singleTap(function(ev){
   $(this).animate({
    rotate:'360deg'
   },1000,'linear',function(){
    this.style.webkitTransform = 'rotate(0)'
   })
  })

  $('.box').on('touchstart',function(){
   $(this).css('background','red')
  })
  $.ajax({
   url:'',
   type:'get',
   dataType:'json',
   cache:false,
   success:function(){
    
   }
  })

The above is the detailed content of Detailed introduction to the basics of JavaScript mobile events and a summary of commonly used event libraries. 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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.

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

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),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function