hammerjs ———— 一个移动端的手势库。

New Hammer 的过程

最简单的使用一个手势的demo

 // 定义 Manager
 var hammertime = new Hammer(element, {});
 // 绑定事件
 hammertime.on('pan', function(e) {
 TODO Logic...
})

  • 调用 Hammer function 初始化

在hammer.js中可以看到下面一段代码用于定义一个Manager(element, options)
element: 手势操作的元素
options: 定义配置参数

function Hammer(element, options) {   
 options = options || {};
    // 定义recongnizers, 如果 options.recongnizers 为 undefined, 默认 'Hammer.defaults.preset'
    options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
    return new Manager(element, options);
}

    • 默认 recongnizers, TapRecognizer 同步注册了 TapRecognizer, 同理 PinchRecognizer 同步注册 RotateRecognizer (也可以外部采用 recognizer.recognizeWith() 注册同步Recognizer.)

      preset: [

        // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
        [RotateRecognizer, {enable: false}],
        [PinchRecognizer, {enable: false}, ['rotate']],
        [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
        [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
        [TapRecognizer],
        [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
        [PressRecognizer]

      ],

    • 绑定事件handler (hammertime.on)

    demo中的 hammertime.on('pan', function(e) { }) 实际上为调用 manager.js 中的 on function

    on: function(events, handler) {
        if (events === undefined) {
            return;
        }
        if (handler === undefined) {
            return;
        }
        var handlers = this.handlers; // bind handlers to Manager.handler
        each(splitStr(events), function(event) {
            handlers[event] = handlers[event] || [];
            handlers[event].push(handler);
        });
        return this; // this = Manager
    },
    

    JUANA
    205 声望777 粉丝

    大龄小白白~ 依旧坚强地过好每一天~