Hammerjs is an excellent, lightweight touchscreen device gesture library that has now been updated to version 2.04, with the 1.0 version somewhat Tianrang, after all, rewriting the event name and adding a number of methods that allow simultaneous monitoring of multiple gestures, custom recognizers, and the ability to identify the sliding direction.
However, for the new version of the HAMMERJS and its lack of Chinese guidelines document, this point I am still the last officer net translation of English documents, write an article to share it with you (in fact, Hammer API is very not how much, the content and layout are very sloppy, the proposal first carefully study examples And then check back. You can also learn from the Hammer series of Aaron's pork-wing articles .
Note: This article translates the "input" referred to in all APIs into "interactive", which actually includes MouseDown, MouseMove, Touchmove, pointercancel events.
General start
Hammerjs is an open source library that recognizes the series of gestures triggered by touch, mouse and pointerevents. It is very small, only 3.96kb after compression, and there is no redundant scripting dependencies.
You can get the latest version of Hammerjs from Github, or download a compressed or uncompressed version of the HAMMERJS source directly.
Click here to get the version change log.
You can also click here to get the older version 1.1.
Version 2.0 changes: Completely rewrite the source code, including the reusable Recognizer (recognizer) , improved the latest mobile browser available touch behavior CSS Properties support, and support the use of multiple hammer instances simultaneously, It's also a cinch for multiple users to use a single device at the same time.
Use
Hammerjs is very simple to use, as long as the library is introduced into the file and a new instance is created:
var New Hammer (myelement, myoptions); Hammertime.on (function(EV) { console.log (EV);});
It will default to this object to add a series of recognizers, including tap< Point, doubletap< double click, press< hold,, horizontal orientation of the pan< pan > and swipe< fast sliding; As well as multi-contact pinch< pinch > and rotate< rotation > recognizer. However, pinch and rotate are not available by default because they can cause elements to get stuck, and if you want to enable them, add these two sentences:
true }); Hammertime.get (True });
To allow the recognizer to recognize pan and swipe in the vertical or full orientation, you can write:
Hammertime.get (' Pan '). Set ({Direction:Hammer.DIRECTION_ALL}), Hammertime.get (' swipe '). Set ({direction: Hammer.direction_vertical});
It is also recommended to add the following meta tags to prevent doubletap or pinch from scaling viewport:
<name= "Viewport" content= "User-scalable=no, Width=device-width, Initial-scale=1, maximum-scale=1 ">
More control
You can set your own recognizer for your instance, although you can write a little bit more code, but it will allow you to control more of the gestures that can be identified:
var New New Hammer.pan ({direction:Hammer.DIRECTION_ALL, threshold:0new Hammer.tap ({ Event: ' Quadrupletap ', Taps:4 }); Mc.on ("Pan", Handlepan); Mc.on ("Quadrupletap", handletaps);
The code above creates an instance (MC) that contains a pan and a quadrupletap gesture, and the recognizer instance executes continuously after they are added (add), and (a recognizer instance) can only recognize one (gesture).
Tips and Tricks 1. Try to avoid pan/swipe in the vertical direction.
Panning operations in the vertical direction are typically used to scroll through your pages, and some (outdated) browsers do not pass events, causing Hammer to recognize these gestures. You can try another alternative way to achieve the same action.
2. Do the test on the device
Sometimes hammer need to make some adjustments, like the rate of swipe or other thresholds, if you're testing on a slower-reacting device, make sure your callback is as simple as possible. Some sites, such as jankfree.org, have specific articles about how to improve the presentation.
3. Remove the highlight effect when Windows Phone clicks
When you tap an element in the IE10 and IE11 on the Windows Phone, there is a small tap highlight, plus this meta tag to cancel the effect:
<name= "Msapplication-tap-highlight" content= "No"/>
4. "How can I not choose the text!" "
Hammer sets a user experience (UX) that is used to enhance the desktop panning operation. As a rule, when you drag a page on a desktop browser, you should be able to select the text normally, but user-select this CSS property disables the feature. If you care about the text selection feature and feel that the desktop level experience doesn't need to be perfect, you can easily cancel this default option--Make sure to do it before creating the instance:
Delete Hammer.defaults.cssProps.userSelect;
5. "After tap, cause a click event to be triggered, I don't want to do this!" ”
This click event, which we call a "ghost click" Event, I created a small function to avoid a touch that led to the click, and Ryan Fioravanti's article gave me great inspiration.
Browser/terminal support
No need to worry that your browser or system is not on the list below, Harmmer can run anywhere except ie8-. Browsers that provide native support for touch behavior (touch-action) have a better experience comparing browsers that are not supported. See the Touch-action page for more information.
Instance
1. Base instance
2. Pan recognizer in vertical direction
3. Simultaneous identification (implemented with recognizewith) pinch and rotate
4. Use Recognizewith to operate Quadrupletap (custom, 4 tap) recognizer
5. singletap< single point > and doubletap< Double click > (with Recognizewith/requirefailure)
More instances can view the library files on GitHub.
Hammer General API
Hammer
Hammer.defaults
Hammer.manager
Hammer.recognizer
Hammer.input Event
Event Object
Constants
Utils
==============================hammer
Creates and returns a manager instance with a collection of default recognizers for the series, which contains such as Tap, Doubletap, Pan, swipe, press, pinch, and rotate recognizers. You should execute it at initialization time, with the following syntax:
Contructor (HtmlElement, [options])
One of the parameters is your page element, and the other is the optional Recognizer option Options,options will be incorporated into Hammer.defaults, of course, the recognizer set defined in Hammer.defaults.preset will be added.
If the recognizer option options are empty, no additional recognizers will be added when initializing:
var myelement = document.getElementById (' Hitarea '); var New Hammer (myelement);
==============================
Hammer.defaults
The default value that is initialized when the instance is created, including the options selector item that you define. Its properties include:
Touchaction: ' Compute '
The value can be compute, auto, pan-y, Pan-x , or none . The default option is to select a correct value for you based on the recognizer.
Domevents:false
Allows Hammer to disable DOM events as well. If you do not disable it will be a bit slow, so the default is disabled. If you want to implement an event delegate, it is recommended that you set it to true.
Enable:true
A function that accepts a Boolean value, or returns a Boolean value. (official website on such a sentence, also did not say specific what role, sweat ~)
Cssprops: {...}
A series of CSS properties that can improve interactive event operations. More details can be found in JSDoc.
Preset: [...]
The default recognizer is installed when Hammer () is called. If a new manager is created, these will be skipped.
==============================
Hammer.manager
The manager is a container for all recognizer instances, which installs an interactive event listener for your element and sets the touch event feature.
Constructor (HtmlElement, [options])
The parameters are your element (HtmlElement) and options, and the options are merged into the Hammer.defaults:
var New Hammer.manager (myelement);
You can use recognizers in the options to set an initialization recognizer, which is an array, as follows:
var New Hammer.manager (myelement, { recognizers: [ // recognizerclass, [options], [ Recognizewith, ...], [Requirefailure, ...] [hammer.rotate], false }, [' Rotate '], [hammer.swipe,{Direction:Hammer.DIRECTION_HORIZONTAL}], ]});
Set (options)
The option to modify a manager instance is recommended, and it can update the value of the touchaction when needed:
true });
Get (String), add (recognizer) and remove (recognizer)
Add a new recognizer instance to the manager, and the order of addition is consistent with the order in which the recognizer executes. The Get method returns the recognizer instance that was added.
Both the Get and remove methods take an event name (in the recognizer) or a recognizer instance as a parameter.
The Add and remove methods also accept a recognizer array as an argument:
// both return instance of Mypinchrecognizermc.get (' pinch '// returns the recognizer Mc.add ([Mysecondrecogizner, Mythirdrecognizer]); Mc.remove (Mypinchrecognizer); Mc.remove (' rotate ' ) ' rotate ']);
On (events, Handler) and. Off (events, [handler])
Listens for events triggered by the added recognizer, or removes those that have been bound. The event is separated by a space in the parameter to handle multiple events:
function (EV) { console.log (Ev.scale);});
Stop ([force])
Stops the recognizer of the current interactive session (stop recognizing for the present input session). When the force parameter is used, the recognizer execution cycle is forced to stop immediately.
Destroy ()
Unbind all interaction events and leave the manager out of action, but it does not unbind any DOM event listeners.
==============================
Hammer.recognizer
Each recognizer is extended from this class, and all recognizers have an enable option with a Boolean or a callback function to enable/disable non-underlying recognizers.
Constructor ([options])
Only options as parameters:
var New // Create a recognizer // Add to Manager instance
Set (options)
Modifies an option in the recognizer instance. This method is recommended, and it can update the value of the touchaction when needed.
Recognizewith (Otherrecognizer) and Droprecognizewith (Otherrecognizer)
It can be helpful to synchronize other recognizers (Otherrecognizer) when the current recognizer is running, when you need to combine pan and swipe gestures at the end, or when you need to pinch and ratate an object at the same time.
When this contact is removed, only the connection on the current recognizer is removed, not the connection on the other recognizer (Otherrecognizer).
Both of these methods support an array of identifiers as parameters.
If the recognizer is added to the manager, the method also supports the event name (string form) of the other recognizer (Otherrecognizer) as a parameter.
Learn more about Recognizewith
Requirefailure (Otherrecognizer) and Droprequirefailure (Otherrecognizer)
The recognizer is executed only if another recognizer (Otherrecognizer) is invalid.
When this contact is removed, only the connection on the current recognizer is removed, not the connection on the other recognizer (Otherrecognizer).
Both of these methods support an array of identifiers as parameters.
If the recognizer is added to the manager, the method also supports the event name (string form) of the other recognizer (Otherrecognizer) as a parameter.
Learn more about Requirefailure
==============================
Hammer.input Events
Hammer.input can trigger a "secret" event that occurs in each receiving interaction, and allows you to do the same with the native interaction. It is a small and powerful feature.
function (EV) { console.log (ev.pointers);});
==============================
Event Object
Each event triggered by a hammer receives an event object that contains the following attributes:
==============================
Constant/constants (this recommendation to refer to source 338 lines, mainly for the flag event contour, can be obtained through the "event object" above the direction, Offsetdirection and other properties)
All constants are defined in the Hammer object, because they are binary identities, and you can manipulate them using bitwise operations. The MDN has some excellent documentation on bit operations.
Azimuth/directions
Used to define the orientation of a recognizer and to read the corresponding value of an event.
Interactive Event/input Events
Hammer matches all interactions (MouseDown, MouseMove, Touchmove, Pointercancel) event types as follows:
Recognizer Status/recognizer states
Define your own state internally by the recognizer:
==============================
Tool/utilshammer.on (element, types, handler)
AddEventListener encapsulation, you can accept multiple event types as parameters:
function (EV) { console.log (ev.type);});
Hammer.off (element, types, handler)
Like Hammer.on, it is the encapsulation of RemoveEventListener and allows multiple event types to be parameters.
Hammer.each (obj, handler)
To traverse an array or object:
function (item, index, SRC) {}); Hammer.each ({A:function(item, key, SRC) {});
Hammer.merge (Obj1, Obj2)
Mix the attributes of the obj2 into the obj1, but the existing properties of OBJ1 are not rewritten:
var options = { false}; var defaults = { true, true, c: [A. ]}; Hammer.merge (options, defaults); // OPTIONS.A = = True // options.b = = False // OPTIONS.C = = [+]
Hammer.extend (Obj1, Obj2)
Extend the properties of the Obj2 to Obj1, but the existing properties of OBJ1 are rewritten:
var = {true, false, c: [obj1]}; var obj2 = { true, c: [4,5,6]}; Hammer.extend (Obj1, obj2); // obj1.a = = True // obj1.b = = True // obj1.c = = [4,5,6]
Hammer.inherit (Child, Base, [properties])
Simple class Inheritance:
functionAnimal (name) { This. Name =name;}functionDog () {animal.apply ( This, arguments);} Hammer.inherit (Dog, Animal, {bark):function() {alert ( This. Name); }});varDog =NewDog (' Spaikie ');d Og.bark (); Simplified form of HAMMER.BINDFN (FN, scope) Function.bind:functionmyFunction (EV) {Console.log ( This= = = Mycontext);//Is true}varMycontext ={A:true, B:false};window.addeventlistener (' Load ', HAMMER.BINDFN (MyFunction, Mycontext),false);
Hammer.prefixed (obj, name)
Get the browser's (prefix) property value:
Hammer.prefixed (Document.body.style, ' userselect '); // returns "Webkituserselect" on Chrome
About the Hammer API is translated here, the remaining pages of the content is less and better read, please consult and understand.
This article is October 8 pen, follow-up because change work, the matter of the city is shelved, dust-laden in the Quadrochromatic box, until today suddenly remembered decided to finish it, for the intention to get started hammer friends to do a reference it (again spit slot Hammer API written very hasty).
Mutual Encouragement ~
Mobile Gesture Library Hammerjs 2.0.4 Official document translation