JavaScript自定义点击事件

时间:2016-04-03 13:52:21

标签: javascript jquery events

我想创建一个自定义事件,例如tap,既可以用于鼠标点击又可以触摸一个元素,因此它可以像任何其他事件一样被附加。现在,我创建了一个mousedown / touchstart / pointerdown处理程序的函数,我将实际的处理程序传递给数据对象,它可以工作,但它并不优雅。这是:

var tap = function(e) {

  var handler=e.data.handler; //handler is passed in data object

  var eventType=e.originalEvent.type.replace('down','').replace('start',''); //touch, mouse or pointer
  var inputDevice=((eventType === 'pointer' && e.originalEvent.pointerType === 'mouse') || eventType === 'mouse') ? 'mouse' : 'touch';
  var endEvent=(eventType === 'touch') ? eventType+'end' : eventType+'up';
  var targetElement=this;

  e.preventDefault();

  $(document).on(endEvent+'.customTap', function(e) {

    var x,y;

    if (eventType === 'touch') {
        x=e.originalEvent.changedTouches[0].clientX;
        y=e.originalEvent.changedTouches[0].clientY;
    }
    else {
        x=e.clientX;
        y=e.clientY;
    }

    //this won't work, if the element has children, to do: iterate over parent elements
    if (document.elementFromPoint(x,y).isSameNode(targetElement)) handler(e); //execute the actual handler

    $(document).off(endEvent+'.customTap');
    e.preventDefault();

  });
}

var attachCustomTap = function($element, handler) {

    var startEvent;
    if (window.PointerEvent) startEvent='pointerdown';
    else startEvent='touchstart mousedown';

    $element.on(startEvent, { handler: handler }, tap);

}

所以我的问题是,是否可以使用类似的东西:

$('button').on('customTap', doSomething);

而不是

attachCustomTap($('button'), doSomething);

0 个答案:

没有答案