自定义滑动事件

by 苹果熊

HTML

<div id="test"></div>

CSS

body {
  height: 600px
}
#test {
  height:200px;
  background:#f60;
}

JavaScript

$(function() {
	(function(){
  	var touch = {}, distance = x = 0, isMove = false
    $(document).on('mousedown', function(e) {
      isMove = true
      touch.el = $(e.target)
      x = e.pageX
    })
    .on('mousemove', function(e) {
      if(!isMove) return
    })
    .on('mouseup', function(e) {
      distance = e.pageX - x
      if(distance > 50) {
        touch.el.trigger('swipeRight')
      }
      if(distance < -50) {
      	touch.el.trigger('swipeLeft')
      }
      touch = {}
      distance = x = 0
      isMove = false
    })

    ;['swipeLeft', 'swipeRight'].forEach(function(eventName) {
    	$.fn[eventName] = function(callback) {
        return this.on(eventName, callback)
      }
    })

    $('#test').on('swipeRight', function() {
    	console.log('右滑动')
    })
    .on('swipeLeft', function() {
    	console.log('左滑动')
    })
  })()
})