hammer.js - need default zoom behaviour + swipe

随声附和 提交于 2019-12-25 18:21:09

问题


I want to make it so swiping over an image will take a user to the previous or next image, depending on the direction of the swipe. That part works great, BUT it removes the ability to zoom in on the image. According to this answer the solution is to enable touchAction: 'auto', but that breaks hammer.js entirely, preventing it from working for swipe at all.

Code:

<script src="../js/hammer.min.js"></script>
<script>
$('.imagecontainer').each(function(){
  var options = {
    touchAction: 'auto',
  };
  var mc = new Hammer(this, options);

  mc.on("swipeleft", function() {
    navTo('jsnavnext');
    return false;
  });
  mc.on("swiperight", function() {
    navTo('jsnavprev');
    return false;
  });
});
</script>

I can get pinch-zoom to work in the least user-friendly way possible with touchAction: 'pan-y' (basically requires the user to make a wacky circle motion), but that's not...great. Ideally I'd like hammer.js to ONLY add swipe navigation and not touch any other default behaviour.


回答1:


I had a problem that was similar. I wanted to be able to detect swipes on a div and also be able to pinch zoom on the div. The swipe listener alone seemed to disable zoom. Adding touchAction:'auto' allowed me to pinch zoom, but it read would both fire my swipe action and scroll (I didn't want it to scroll, just wanted to fire the swipe action). The key part of the solution I have here is using recognizeWith, and then call preventDefault on panstart and panmove. This leaves me with just the desired pinch zoom and swipes

Here's my solution:

  var target = document.getElementById("target-div")
  var mc = new Hammer(target, {touchAction: 'auto' });

  mc.add( new Hammer.Pan({
    direction: Hammer.DIRECTION_ALL,
    threshold: 0 }) );

  mc.add(new Hammer.Swipe({
    direction: Hammer.DIRECTION_ALL,
    threshold: 1,
    velocity:0.1
  })).recognizeWith(mc.get('pan'));

  mc.on('panstart panmove', function(ev) { ev.preventDefault(); });

  mc.get('pinch').set({ enable: true });

  mc.on("pinch", function(ev) {
  //do anything you need to here, or not 
  });

  mc.on("swipeleft", function(ev) {
  //do something
  }

  mc.on("swiperight", function(ev) {
  //do something
  }

I am still new to hammer.js, but I have noticed a lot of issues on github where people are trying to combine multiple gestures on the same element. I hope this helps!



来源:https://stackoverflow.com/questions/45392027/hammer-js-need-default-zoom-behaviour-swipe

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