Extend jQuery's .on() to work with mobile touch events

守給你的承諾、 提交于 2019-12-08 23:45:12

问题


I am attempting to use the jQuery mobile events without the rest of jQuery mobile.

https://github.com/jvduf/jquery-mobile-events/blob/master/jquery.mobile.events.js

That snippet enables them all, and works fine, but not with the .on() event handler. E.g:

$('a').on('tap',function(){
    console.log('Hi there!');
});

However it does work with .live(), but that is now depreciated.

So my question; is there a a way to extend the .on() functionality to include the tap event and others? Full list below:

  • touchstart
  • touchmove
  • touchend
  • orientationchange
  • tap
  • taphold
  • swipe
  • swipeleft
  • swiperight
  • scrollstart
  • scrollstop

Thanks :)


回答1:


However it does work with .live(), but that is now depreciated.

So I take it that you want to use event delegation to preserve those events on replaced elements. That would mean that this:

$('a').on('tap',function () {
    console.log('Hi there!');
});

would need to change to something like:

$(document).on('tap', 'a', function () {
    console.log('Hi there!');
});

in order for it to behave the same as $("a").live("tap", ...




回答2:


Maybe it should be better to extend the JQuery event code for mobile and desktop.

One way to do this is to use the JQuery vmouse (virtual mouse) plugin.

From vmouse plugin comments:

// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"

For a better explanation, see https://coderwall.com/p/bdxjzg

vmouse plugin: https://github.com/jquery/jquery-mobile/blob/master/js/jquery.mobile.vmouse.js

Also see this link about current state of (touch) events: http://blogs.adobe.com/adobeandjquery/2011/03/07/the-current-state-of-touch-events/



来源:https://stackoverflow.com/questions/9311079/extend-jquerys-on-to-work-with-mobile-touch-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!