Page control–Mobile development gesture library Hammer.JS usage documentation

Article directory

        • Hammer.js introduction:
        • Notice:
    • 1. Plug-in introduction method
        • 1. Introduce directly using script tags on the page
        • 2. Introduction via npm
    • 2. Basic usage demonstration
        • 1. css:
        • 2. html:
        • 3. JavaScript:
    • 3. Event types monitored by Hammer.js
        • 1. pan event (drag and drop):
        • 2. pinch event (pinch to zoom):
        • 3. press event (long press)
        • 4. rotate event (rotation)
        • 5. swipe event (swipe)
        • 5. tap event (click)
    • 4. Hammer object:
        • 1.Hammer.defaults
          • Property description:
            • 1. touchAction:
            • 2. domEvents: false:
            • 3. enable:true:
            • 4. cssProps:
            • 6.preset:
        • 2. Hammer.Manager:
        • 3. Hammer object instance methods:
          • 1.hammers.get(string).set(options):
          • 2.add(Recognizer) and remove(Recognizer):
          • 3.hammers.on(events, handler processing function) and hammers.off(events, [handler])
          • 4.hammers.stop([force])
          • 5.hammers.destroy()
        • 4. Hammer.Recognizer
          • 1.recognizeWith(otherRecognizer)
Hammer.js introduction:
  • Hammer.js is a lightweight gesture plug-in library for touch screen devices. It can help us identify touches, drags, long presses, slides, and fingers encountered during mobile development. Common user gesture operations such as panning, pinching and zooming with two fingers.

  • Hammer.js does not need to rely on any JS library, and its size is small. The size of Hammer.js in the production environment is 7.34KB.

  • Hammer.js official website address http://hammerjs.github.io/getting-started/.

  • Hammer.js download address:

    1. Official version: http://hammerjs.github.io/dist/hammer.min.js
    2. Development version: http://hammerjs.github.io/dist/hammer.js
    3. Github source code address: https://github.com/hammerjs/hammer.js/tree/master/
  • Hammer can run anywhere except IE8-. If the browser provides native support for touch-action, it will have a better experience than those browsers that do not support it. Learn more by checking out the touch-action page.

Note:
  • This document is for Hammer.js version 2.0.8. The download links above are all for version 2.0.8.
  • Hammer.js 2.0.8 has completely rewritten the entire plugin. In this version, it features reusable gesture recognizers and improved support for the latest mobile browsers by using the touch-action css property where possible. . Multiple Hammer instances are supported simultaneously, so multi-touch is possible.
  • If you want to know about the previous version, you can visit https://github.com/hammerjs/hammer.js/tree/1.1.x
  • This plug-in provides mobile gesture monitoring function, but does not encapsulate the event feedback corresponding to the gesture, so the event processing logic needs to be defined by yourself.
  • This JS plug-in is the most comprehensive and new mobile gesture that I can find currently.
  • This document is compiled and compiled with reference to official documents.

1. Plug-in introduction method

1. Introduce directly using script tags on the page

The above files are imported from online. You can download them locally and then import them.

2. Introduction via npm

npm install hammerjs

2. Basic usage demonstration

1. css:
<style>

test{<!-- -->
width: 200px;
height: 200px;
background-color: royalblue;
}

</style>

2.html:

3. JavaScript:
  1. Get dom:

    var tst = document.querySelector(.test)

  2. Create a Hammer instance object:

    var hammers = new Hammer(tst)

    • Hammer is a constructor that returns an instance object Manager with a set of default gesture recognizers.

    • When creating an instance object, you need to pass two parameters. The first parameter is a DOM element on the page, and the second parameter is an optional parameter. It can receive an array, and this array can write the gesture recognition that needs to be used. If this parameter is not given, the default gesture recognizers such as tap, doubletap, pan, swipe, press, pinch, and rotate will be enabled by default, and no additional recognizers will be enabled.

  3. A few simple lines of code to monitor sliding and long press events:

var hammers = new Hammer(document.getElementById('test'));
hammerTest.on('pan panmove swipe swipeup press pressup', function(ev) {<!-- -->
    console.log(ev.type);
});
//By default, it adds a set of tap, doubletap, press, horizontal pan and swipe and multi-touch pinch and rotate recognition. By default, the shrink recognizer and rotation recognizer are disabled because they block the element, but they can be enabled by calling the following command
hammertime.get('pinch').set({<!-- --> enable: true });
hammertime.get('rotate').set({<!-- --> enable: true });
  1. Click to view basic examples

3. Event types monitored by Hammer.js

1. pan event (drag and drop):

In the bound dom area, a finger is put down and moved, that is, the finger on the touch screen is pressed and moved, similar to a drag operation. This event is commonly used in screen touch development.

Event name Description
pan Press and hold your finger to move
Panstart Start dragging (press your finger and start moving)
Panmove Draging (press and move your finger)
Panend Drag ends (release your finger, Stop moving)
Pancancel Cancel drag
Panleft Drag left
Panright Drag right
Panup Drag up
Pandown Drag down
  • Notice:

    The drag event in the vertical direction is generally used to scroll the page, so the hammer does not enable the vertical pan event in the vertical direction by default.

    If you need to use the vertical pan event, you need to enable the vertical direction of the pan event through the instance object:

    hammers.get('pan').set({

    direction:Hammer.DIRECTION_ALL

    })

2. pinch event (pinch to zoom):

In the bound dom area, two fingers (default is two fingers, multi-finger touch needs to be set separately) or multiple fingers move relative (getting closer) or move towards each other (getting further away)

Event name Description
Pinchstart Multi-touch starts (press with two fingers)
Pinchmove Multi-touch in progress (press with two fingers and start moving )
Pinchend End of multi-touch (release two fingers)
Pinchcancel Multi-touch cancel
Pinchin The distance between multi-touch fingers is getting closer and closer (commonly used to zoom out)
Pinchout The distance between the two fingers becomes farther and farther during multi-touch (commonly used for zooming in)

Notice:

  • Pinchin and Pinchout may also trigger the default event of the browser’s page zooming in and out, so when using these two methods, it is best to disable the browser’s zooming.

  • Pinch events are not available by default because they may cause elements to get stuck. If you want to use them, you must first use the following method to enable this event:

    hammers.get('pinch').set({

    ? enable = true

    })

3. press event (long press)

The click event of the touch screen version in the bound dom area. This event is equivalent to the Click event on the PC. This event cannot contain any movement. The minimum pressing time is 500 milliseconds. It is often used for the “copy and paste” functions we use on mobile phones. ” and other functions.

Event name Description
press Press and hold
pressup release

Notice:

  • If the bound dom area contains text elements, using the press event will trigger the default text selection function. If you do not want this to happen, specify the CSS attribute: user-selector:none for the dom element.

[Note] Each event identifier can be regarded as an instance. We can assign an identifier to a variable such as:

 mc.add( new Hammer.Tap({<!-- --> event: 'tap4', taps: 4 }) );
  mc.on('tap4',(ev)=>{<!-- -->
      console.log(ev.type)
  })
\t
4. rotate event (rotation)

Triggered when two or more fingers rotate in a circle within the bound dom area (just like two fingers tightening a screw).

Event name Description
rotatestart Rotation starts (press and hold with two fingers and start rotating)
rotatemove Rotation process
rotateend Rotation ends
rotatecancel Cancel rotation

Notice:

  • The rotate event, like pinch, will cause the DOM element to be stuck, so this event is not enabled by default. If you want to use it, you need to enable the rotate event through the following code:

    hammers.get('rotate').set({

    ? enable = true

    })

5. swipe event (swipe)

Within the bound dom area, a finger quickly slides on the touch screen. That is the sliding event we usually use most.

Event name Description
swipe Swipe
swipeleft Swipeleft
swiperight Toward Swipe right
swipeup Swipe up
swipedown Swipe down

Notice:

  • Generally speaking, vertical sliding can be used to scroll the page, so swipe does not enable Swipeup and Swipedown events by default. If you need to use it, you can set the direction of the Swipe event through the instance object:

    hammers.get('swipe').set({

    direction:Hammer.DIRECTION_ALL

    })

    DIRCTION_ALL means turning on all directions of swipe

    In addition to locative nouns, you can also use numerical values

5. tap event (click)

This event is triggered when a finger taps or clicks in the specified dom area (similar to click on the PC). The maximum click time of this event is 250 milliseconds. If it exceeds 250 milliseconds, it will be processed according to the Press event.

Event name Type
tap Click
doubletap Double-click

4. Hammer object:

1.Hammer.defaults
  • Hammer.defaults is the initialization default value when generating an instance object, including the defined options recognizer list. That is, in new Hammer is the gesture recognizer that needs to be turned on as the second parameter. Hammer.defaults is also an object.

Attribute description:
1. tocuhAction:

Recognizer options, whose values can be compute, auto, pan-y, pan-x or none. The default option will choose the correct value for you based on the recognizer.

2. domEvents: false:

Whether to disable DOM events, pointed out by the hammer object, the value is a Boolean value. If you want to implement event delegation, it is recommended that you set it to true.

3. enable:true:

All recognizers will have an enable option with a value of boolean or a callback function to enable/disable non-low-level recognizers.

4. cssProps:

A series of CSS properties that can improve interactive event operations. More details can be found in JSDoc.

6. preset:

The default recognizer is installed when a Hammer instance is created. If you create a new Manager (listener container), these will be overwritten.

2. Hammer.Manager:

The Manager is a container for all recognizer instances. It installs interaction event listeners for your elements and sets some characteristics for touch events.

You can use Hammer.Manager to generate instance objects. This method can set some characteristics of the listener when generating instance objects, such as:

var hammer = new Hammer.Manager(myElement, {<!-- -->
    recognizers: [
        // RecognizerClass, [options], [recognizeWith, ...], [requireFailure, ...]
        [Hammer.Rotate],
        [Hammer.Pinch, {<!-- --> enable: false }, ['rotate']],
        [Hammer.Swipe,{<!-- --> direction: Hammer.DIRECTION_HORIZONTAL }],
    ]
    //The parameters are your element (HTMLElement) and options (options). The options passed are the names of the gesture recognizers, which are then merged into the preset array in Hammer.defaults.
});

Set the characteristics of the recognizer by setting the value in the recogizers property, which is an array

3. Hammer object instance methods:
1.hammers.get(string).set(options):

The get method can be understood as getting the recognizer. This method requires a recognizer as a parameter. After obtaining it, click the .set method to modify the characteristics of the recognizer when needed, such as controlling whether to enable this recognizer, setting pen, swipe recognition direction of the device

(The get method is pointed out by the generated instance object)

grammar:

mc.get('swipe').set({<!-- --> enable: true });
//Enable swipe fast sliding event recognizer
2.add(Recognizer) and remove(Recognizer):

(Recognizer means recognizer)

Add a new Recognizer instance to the Manager in the same order as the recognizers are executed.
Both the get and remove methods take an event name (in the recognizer) or recognizer instance as a parameter.
The Add and remove methods also accept an array of recognizers as a parameter

(The add and remove methods are pointed out by the generated instance object)

hammers.add(myPinchRecognizer);
//Add a custom gesture recognizer (how to create a custom gesture recognizer will be explained below)
hammers.add([mySecondRecogizner, myThirdRecognizer]);
//Add multiple custom gesture recognizers, the parameter format is an array
hammers.remove(myPinchRecognizer);
//Remove a custom gesture recognizer
hammers.remove('rotate');
//Remove rotate gesture
hammers.remove([myPinchRecognizer, 'rotate']);
//Remove multiple gesture recognizers, the parameter format is an array
3.hammers.on(events, handler processing function) and hammers.off(events, [handler])

The hammers.on method can listen for events triggered by added recognizers:

hammers.on('tap swipe doubleTap',function(ev){<!-- -->
          if(ev.type = 'tap'){<!-- -->
console.log('tap')
}else if(ev.type = 'doubleTap'){<!-- -->
              console.log('doubleTap')
          }else{<!-- -->
              console.log('swipe')
          }
        })
  //hammers.on can monitor events triggered by multiple recognizers at the same time. The method is to pass each recognizer as a parameter separated by spaces.
  //The second parameter is the event processing function. By judging ev.type, you can determine which recognizer is currently triggering the event, so as to perform different operations.

The hammers.off method removes some bound events:

hammers.off('tap swipe doubleTap')
4.hammers.stop([force])

Stops the recognizer for the current interactive session. When the force parameter is used, the recognizer execution cycle will be forced to stop immediately.

5.hammers.destroy()

Unbinds all interaction events and disables the manager, but it does not unbind any DOM event listeners.

4. Hammer.Recognizer

Each recognizer extends from this Recognizer class. All recognizers will have an enable option whose value is boolean or a callback function to enable/disable non-low-level recognizers.

Print Hammer.Recognizer on the console:

[Note] The Recognizer cannot be obtained using the generated instance object, and can only be clicked through the Hammer object.

1.recognizeWith(otherRecognizer)

You can use the recognizeWith() method when the current recognizer needs to run synchronously or recognize other recognizers (otherRecognizer). For example, when you need to monitor the swipe gesture recognizer when the pan recognizer is triggered, or you need to listen to the swipe gesture recognizer at the same time. Pinch scales and ratate rotates a DOM element.

recognizeWith()) needs to pass a parameter, which is a recognizer name in string format. If there is a custom recognizer, it can also be passed in as a parameter, provided that the custom recognizer must have passed hammers. The add method is added to the Manager recognizer container, and an array storing the name of the recognizer can be passed in as a parameter. This allows multiple recognizers to be monitored at the same time when a recognizer is triggered.

Specific usage:

 var hammers = new Hammer();
hammers.get('swipe').set({<!-- -->
        enable:'true',
        direction:Hammer.DIRECTION_ALL
    })
hammers.get('pan').set({<!-- -->
        enable:'true',
        direction:Hammer.DIRECTION_ALL
    })
hammers.get('pinch').set({<!-- -->
        enable:'true'
    })
hammers.get('rotate').set({<!-- -->
        enable:'true'
    })
// The vertical direction of swipe and pan as well as pinch and rotate are disabled by default, so you need to enable them first with the above methods.
var pans = new Hammer.Pan();
var swipes = new Hammer.Swipe();
pans.recognizeWith(swipes)
mc.on("pan swipe", function(ev) {<!-- -->
    myElement.textContent + = ev.type + " ";
});
//Now, you can monitor swipe while panning.
//If you need to monitor rotation and scaling at the same time
var rotates = new Hammer.Rotate();
var pinch = new Hammer.Pinch();
rotates.recognizeWith(swipes);
//Now, you can monitor the pinch while rotating.
mc.on("pinch rotate", function(ev){<!-- -->
    myElement.textContent + = ev.type + " ";
});

Examples of using the recognizeWith() method recommended by the official website: simultaneously recognizing (implemented with RecognizeWith) Pinch and Rotate