2-19 hammerjs 使用


html



   
  
    
Swipe Left or Right

css

html, body {
  height: 100%;
}

body {
  background-color: #000;
  color: #FFF;
  margin: 0;
}

.flex-column {
  display: flex;
  flex-direction: column;
}

.center-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.square {
  width: 90px;
  height: 90px;
  margin: 30px;
  background-color: #7E57C2;
  transition: transform 300ms ease-out;
}

js

// Get a reference to an element
var square = document.querySelector('.square');

// Create a manager to manager the element
var manager = new Hammer.Manager(square);

// Create a recognizer
var Swipe = new Hammer.Swipe();

// Add the recognizer to the manager
manager.add(Swipe);

// Declare global variables to swiped correct distance
var deltaX = 0;
var deltaY = 0;

// Subscribe to a desired event
manager.on('swipe', function(e) {
  deltaX = deltaX + e.deltaX;
  var direction = e.offsetDirection;
  var translate3d = 'translate3d(' + deltaX + 'px, 0, 0)';
  console.log(e)
  if (direction === 4 || direction === 2) {
    e.target.innerText = deltaX;
    e.target.style.transform = translate3d;
  }
});

manager.on('swipeleft', function(e) {
  console.log('left 移')
})
manager.on('swiperight', function(e) {
  console.log('right 移')
})